struct sockaddr_in sa; |
struct sockaddr_in { |
// IN: The char array 'hostname' // OUT: The hostent struct hp // OUT: A partially filled in sockadd_in struct sa struct sockadd_in sa; struct hostent *hp; hp = gethostbyname(hostname); sa.sin_family = hp->h_addrtype; bcopy((char *)hp->h_addr, (char *)&sa.sin_addr, hp->h_length); |
You also need to fill in the portnumber. If it is a well known
service
(like telnet), you can search for it by name using getservbyname() or look in the file /etc/services. If it is a service
you made, you can pick your own portnumber. Remember that ports
less
than 1024 are reserved for the superuser. Also, remember that the
portnumber needs to be in network byte order. The htons()
function
converts a host short to a network short, and ntohs() does the
opposite.
Since portnumbers are shorts, those are the functions you want.
// IN: the port number 'port'. // OUT: The sockaddr_in struct with the portnumber set sa.sin_port = htons(port); |
// IN: A host entry 'hp' for the address family
// Out: A socket 's' s = socket(hp->h_addrtype, SOCK_STREAM, 0); |
// IN: A socket 's' // IN: An address to connect to 'sa' // OUT: A file descriptor 'fd' ready to use. // NOTE: fd is less than zero on error int ret = connect(s, (struct sockaddr *)&sa, sizeof(sa)); if (ret < 0) { perror("Unable to connect the address to the socket"); } |
// READING // IN: A length 'len' to read // IN: A char array 'buf' which better be at least 'len' long // IN: A file descriptor // OUT: The length read 'ret' which is less than zero on error len = read(fd, buf, len); |
/ WRITING // IN: A length 'len' to write // IN: A char array 'buf' which better be at least 'len' long // IN: A file descriptor // OUT: The length written 'ret' which is less than zero on error len = write(fd, buf, len); |
int MakeSocket(char *host, int port) { int s; int len; struct sockaddr_in sa; struct hostent *hp; struct servent *sp; int portnum; int ret; hp = gethostbyname(host); bcopy((char *)hp->h_addr, (char *)&sa.sin_addr, hp->h_length); sa.sin_family = hp->h_addrtype; sa.sin_port = htons(port); s = socket(hp->h_addrtype, SOCK_STREAM, 0); ret = connect(s, (struct sockaddr *)&sa, sizeof(sa)); cout << "Connect to host " << host << " port " << port << endl; return s; } main() { int fd = MakeSocket("euclid.nmu.edu", 25); write(fd, "Hello", 5); } |