Open System Services Programmer's Guide

Example 43 Using AF_INET in an OSS Server Process
/* server2.c
*
* Simple OSS server example using OSS socket APIs
* for communication between requester and server.
*
* This server accepts AF_INET stream socket connections on
* a listening port. Data requests are handled by printing
* the data and then replying back to the requester with the
* original data. The server exits when idle for 60 seconds.
*/
#define _XOPEN_SOURCE_EXTENDED 1 /* needed for OSS sockets */
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netdb.h>
int fd, listenfd, newfd, highfd, fdcount, readycount, bytesread;
struct sockaddr_in addr; /* socket address (family,addr,port) */
struct timeval timeval; /* timeout structure for select() call */
fd_set fdset, rdset; /* set of fds, set of fds ready for reading */
#define IDLE_PERIOD 60 /* 60 seconds *
#define BUFF_LEN 1024 /* buffer size */
char msg_buff[BUFF_LEN+1]; /* one buffer is enough for all connections */
int main(int argc, char **argv)
{
printf("Server starting\n");
/* create AF_INET stream socket ... if error, then exit(1) */
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket() call failed [errno %d]\n", errno);
exit(1);
}
/* Get server port from the command line or use default 12345 */
if (argc > 1)
addr.sin_port = (short)atoi(argv[1]); /* use command line arg */
else
addr.sin_port = 12345; /* use default */
addr.sin_family = AF_INET; /* internet address family */
addr.sin_addr.s_addr = gethostid(); /* assume server on our host */
/* bind socket to address ... if error, then exit(1) */
if (bind(fd, (const struct sockaddr *)&addr, sizeof(addr)) < 0)
{
printf("bind() call failed [errno %d]\n", errno);
exit(1);
}
/* make the socket a listening socket... if error then exit(1) */
if (listen(fd, 5) < 0)
{
printf("listen() call failed [errno %d]\n", errno);
exit(1);
}
Interprocess-Communication Interoperability 179