char localhostname[255]; |
struct sockaddr_in { |
// IN: The char array 'localhostname' // OUT: The hostent struct hp // OUT: A partially filled in sockadd_in struct sa struct sockadd_in sa; struct hostent *hp; hp = gethostbyname(localhostname); 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(portnum); |
// 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: The backlog level 'BACKLOG' // IN: Our own address in the struct sockaddr_in 'sa'. // OUT: The socket is now associated with the address 'sa'. ret = bind(s, (struct sockaddr *)&sa, sizeof(sa)); listen(s, BACKLOG); |
// IN: A
socket 's' // OUT: A sockaddr with the client's IP number 'client' // OUT: A file descriptor to connected to the client struct sockaddr client; unsigned int client_len = sizeof(client); int fd = accept(s, (struct sockaddr *)&client, &client_len) |
// 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 MakeServerSocket(int *port) { |