All about programming in GNU/LINUX

Network Programming in GNU/LINUX:Introduction on building a server application in GNU/LINUX using C socket API’s

/*This is an Introduction on building a server application in GNU/LINUX using C socket API’s*/
/*Run this program and issue “netstat -ant | grep 7004” in another terminal, you can see the server listening */

/*accept system call doesnot return till either it encounters an error or gets a connection from a client(such system calls are called as blocking system call */
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
    int sd,len;
    struct sockaddr_in servaddr,cliaddr;//socket structure
    sd=socket(AF_INET,SOCK_STREAM,0);/*elementary call in any client server application to create an socket*/

    bzero(&servaddr,sizeof(servaddr));//to initialize all elements of the structure to zero
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);//To assian a arbitrary IP to the server
    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(7004);//port on which the server listens
    bind(sd,(struct sockaddr *)&servaddr,sizeof(servaddr));/*assign the IP and port information to the socket */
    listen(sd,5);/*Listen for incoming coonections */
    len=sizeof(cliaddr);
    accept(sd,(struct sockaddr *)&cliaddr,&len);/*accept the incoming connections*/
    return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s