Archive for January, 2012


TCP Client/Server – UNIX Network Programming….

January 25, 2012


TCP EchoServer: main Function.

Create socket , bind server’s well known port.

A TCP socket is created. An Internet socket structure is filled with the wildcard address (INADDR_ANY) and the server’s well known port (SERV_PORT) , whichis defined 9877 in our unp.h header. Binding the wildcard address tells the system is multihomed. Our choice of the TCP port number is based on Figure 2. It should be greater than 1023 ( we don not need a reserved port) , greater than 5000 (to avoid conflict with the ephermal ports allocated by many Berkeley-derived implementations) , less than 49152 ( to avoid conflict with the “correct” range of ephermal ports) , and it should not conflict with any registered port. The socket is converted into a listening socket by listen.

TCP Echo Server:-

#include “unp.h”


main (int argc , char **argv)


int listenfd , connfd;

pid_t    childpid;

socklen_t clilen;

struct sockaddr_in cliaddr , servaddr;

listenfd = Socket (AF_INET , SOCK_STREAM, 0);

bzero(&servaddr , sizeof(servadr));

servaddr.sin_family = AF_INET;

servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

servaddr.sin_port = htos(SERV_PORT);

Bind(listenfd , (SA *) &servaddr , sizeof(servaddr));

Listen(listenfd , LISTENQ);

for ( ; ; ) {

clilen = sizeof (cliaddr);

connfd = Accept(listenfd , (SA *) &cliaddr , &clilen) ;

if (  (childpid = Fork () ) == 0 )  {    /*child process*/

Close(listenfd);                                 /*close listening socket*/

str_echo(connfd);                           /* process the request */

exit(0) ;


Close(connfd);                                    /*parent closes connected socket */



Our simple example above is an echo server that performs the following steps:-

1. The client reads a line of text from its standard input and writes the line to the server.

2. The server reads the line from its network input and echoes the line back to the client.

3. The client reads the echoed line and prints it on standard output.


Wait for client connection to complete.

The Server blocks in the call to accept , waiting for a client connection to complete.

Concurrent server.

For each client , fork spawns a child , and the child handles the new client . The child closes the listening socket and the parent closes the connected socket. The child then calls str_echo to handle the client.

p/s:- Well ,this week I’m busy with scheduled for interview as a Java Programmer. CES2012 had just finished this month , heard that it had a great feedback from people all around the world.  This week I’m busy studying Middleware and how to implement it in Operating System such as Windows and Linux – example – Oracle , WebSphere , WebLogic , …and much more..

Well folks , that’s all for this week .. Have a nice great weekend ahead…and for the Chinese people , Happy Chinese New Year – Gong Xi Fa Chai…