Thursday, August 2, 2012

Simple Client-Server network Program using TCP/IP stream sockets


This is a simple socket program, in which client sends a message to the server and server replies to the client. The server is waiting for the client process connections.

Server Program:
                                              server.c
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h> // for networkbyte order (htons(),htonl())
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>


int main()
{
    struct sockaddr_in saddr,caddr;
    int len,listenfd,sessfd,ret,retb;
    char buff[10]={0};




    listenfd = socket(AF_INET,SOCK_STREAM,0);
    if(listenfd == -1) {
        perror("socket ");
        return -1;   
    }
   
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    saddr.sin_port = htons(5678);
    len = sizeof(saddr);


    retb=bind(listenfd,(struct sockaddr *) &saddr, len);
    if(retb == -1) {
        perror("bind ");
        return -1;
    }
   


    listen(listenfd,5);
   
    while(1) {
        printf("Server Waiting...\n");
        sessfd = accept(listenfd,(struct sockaddr *)&caddr,&len);
        if( sessfd< 0 ) {
            perror("accept: ");
            return -1;
        }
        read(sessfd,&buff,sizeof(buff));
       
        printf("server read: %s \n",buff);
        memset(buff,'\0',sizeof(buff));
        strcpy(buff,"hai user");
        write(sessfd,&buff,sizeof(buff));
       
       
        close(sessfd);
    }
    close(listenfd);
return 0;
}


Client Program:
                                client.c
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h> // for networkbyte order (htons(),htonl())
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>


int main()
{
    struct sockaddr_in saddr;
    int len,sockfd,ret;
    char buff[10]="hello";


    sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd == -1) {
        perror("socket: ");   
    }
   
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    saddr.sin_port = htons(5678);
   
    len = sizeof(saddr);


    ret = connect(sockfd,(struct sockaddr *)&saddr,len);
    if(ret <0 ) {
        perror("connect: ");
        return -1;
    }
    write(sockfd,&buff,sizeof(buff));
    memset(buff,'\0',sizeof(buff));
    read(sockfd,&buff,sizeof(buff));
   
    printf("Client Read: %s\n",buff);
   
    close(sockfd);
return 0;
}

No comments:

Post a Comment