// Prepare a description of server address criteria.
struct addrinfo addrCriteria;
memset(&addrCriteria, 0, sizeof(addrCriteria));
addrCriteria.ai_family = AF_INET;
addrCriteria.ai_flags = AI_PASSIVE;
addrCriteria.ai_socktype = SOCK_STREAM;
addrCriteria.ai_protocol = IPPROTO_TCP;
// Lookup a list of matching addresses
struct addrinfo *servAddr;
if ( getaddrinfo( NULL, PORT_NUMBER, &addrCriteria, &servAddr) )
printf( "Can't get address info\n" );
// Try to just use the first one.
if ( servAddr == NULL )
printf( "Can't get address\n" );
// Create a TCP socket
int servSock = socket( servAddr->ai_family, servAddr->ai_socktype,
servAddr->ai_protocol);
if ( servSock < 0 )
printf( "Can't create socket\n" );
// Bind to the local address
if ( bind(servSock, servAddr->ai_addr, servAddr->ai_addrlen) != 0 )
printf( "Can't bind socket\n" );
// Tell the socket to listen for incoming connections.
if ( listen( servSock, 5 ) != 0 )
printf( "Can't listen on socket\n" );
// Free address list allocated by getaddrinfo()
freeaddrinfo(servAddr);
// Wait for a client to connect
struct sockaddr_storage clntAddr; // Client address
// Set length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);
int sock = accept( servSock, (struct sockaddr *) &clntAddr, &clntAddrLen);
if ( sock < 0 )
printf( "Can't accept on socket\n" );
// Buffer to receive into, but we never really use it.
char buffer[ BLOCK_SIZE ];
// Try to read all want from the socket.
int count = read( sock, buffer, bytesToRecv );
close( sock );
close( servSock );