TCP/IP Programming Manual

int new_s;
int dcount;
u_short port;
struct hostent *hp;
const char *ap;
/* Declares sockaddr_in structures. The use of this type of
structure implies communication using the IPv4 protocol. */
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
int clientaddrlen;
char response[MAXBUFSIZE] = " This is the server's response";
/* Creates an AF_INET socket. The socket type SOCK_STREAM is
specified for TCP or connection-oriented communication. */
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit (0);
}
/* Clear the server address and sets up server variables. The socket
address is a 32-bit Internet address and a 16-bit port number on
which it is listening.*/
bzero((char *) &serveraddr, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
/* Set the server address to the IPv4 wild card address
INADDR_ANY. This signifies any attached network interface on
the system. */
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(SERVER_PORT);
if (bind(s, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
/* Binds the server's address to the AF_INET socket. */
perror("bind");
exit(2);
}
while (1) {
clientaddrlen = sizeof(clientaddr);
/*Accept a connection on this socket. The accept call places the
client's address in the sockaddr_in structure named clientaddr. */
new_s = accept(s, (struct sockaddr *)&clientaddr, &clientaddrlen);
if (new_s < 0) {
perror("accept");
continue;
}
/* Receive data from the client. */
dcount = recv(new_s, databuf, sizeof(databuf), 0);
if (dcount <= 0) {
perror("recv");
FILE_CLOSE_((short)new_s);
continue;
}
databuf[dcount] = '\0';
/* Retrieve the client name using the address in the sockaddr_in
structure named clientaddr. A call to gethostbyaddr expects an
IPv4 address as input. */
hp = gethostbyaddr((char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
/* Convert the client's 32-bit IPv4 address to a dot-formatted
Internet address text string. A call to inet_ntoa expects an
Programs Using AF_INET Sockets 211