Saturday, November 8, 2008

Echo server/client using tcp/ip sockets in c

2 files

1. client.c

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>  
#include <arpa/inet.h>
#include <stdio.h>

#define PORT 2080

main()
{
        int sock1,sock2,clength;
        char str1[100],str2[100];
        sock1 = socket(AF_INET,SOCK_STREAM,0);
        struct sockaddr_in serv,cli;
        serv.sin_port = htons(PORT);
        serv.sin_family = AF_INET;
        serv.sin_addr.s_addr = inet_addr("127.0.0.1");
        connect(sock1, (struct sockaddr *)&serv,sizeof(serv));
        printf("client connecting\n");
        printf("enter a string\n");
        fgets(str1,100,stdin);
        write(sock1,str1,100);
        printf("\nString sent to server, waiting for reply");
        read(sock1,str2,100);
        printf("\nserver replied : %s",str2);
        return 0;
}


2. server.c :

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>  
#include <arpa/inet.h>
#include <stdio.h>

#define PORT 2080

main()
{
int sock1,sock2,clength;
char recv[100];
sock1 = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serv,cli;
serv.sin_port = htons(PORT);
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sock1,(struct sockaddr *)&serv,sizeof(serv));

listen(sock1,5);
clength = sizeof(cli);
sock2 = accept(sock1,(struct sockaddr*)&cli,&clength);
printf("\n Client connected");
read(sock2,recv,100);
printf("\nClient said: %s",recv);
write(sock2,recv,100);
return 0;
}

No comments:

Blog Archive