TCP/IP Programming Manual

/* Declare a sockaddr_storage structure named clientaddr. The use
of this type of structure enables your program to be protocol
independent. */
sockaddr_storage clientaddr;
char response[MAXBUFSIZE] = " This is the server's response";
/* Create an AF_INET6 socket. The socket type SOCK_STREAM is
specified for TCP or connection-oriented communication. */
if ((s = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit (0);
}
/* Clear the server address and sets up the server variables. */
bzero((char *) &serveraddr, sizeof(struct sockaddr_in6));
serveraddr.sin6_family = AF_INET6;
serveraddr.sin6_addr = in6addr_any;
serveraddr.sin6_port = htons(SERVER_PORT);
/* Bind the server's address to the AF_INET socket. */
if (bind(s, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0){
perror("bind");
exit(2);
}
/* Listen on the socket for a connection. The server queues up
to SOMAXCONN pending connections while it finishes processing the
previous accept call. See sys_attrs_socket(5) for more information on
the socket subsystem kernel attributes. */
if (listen(s, SOMAXCONN) < 0) {
perror("listen");
FILE_CLOSE_((short)s);
exit(3);
}
while (1) {
clientaddrlen = sizeof(clientaddr);
/* Clear the client address. */
bzero((char *)&clientaddr, clientaddrlen);
/* Accept a connection on this socket. The accept call places
the client's address in the sockaddr_storage 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';
printf("Request received from");
ni = getnameinfo((struct sockaddr *)&clientaddr,
clientaddrlen, node, sizeof(node), NULL, 0, NI_NAMEREQD);
if (ni == 0)
printf(" %s", node);
Using AF_INET6 Sockets 239