TCP Server and Client


TCP SERVER

#include <stdio.h>

#include <sys/socket.h>

#include <sys/types.h>

#include <arpa/inet.h>

#include <string.h>

int main(void)

{

int s, len;

char buf[BUFSIZ];

struct sockaddr_in remote_addr;

memset(&remote_addr, 0, sizeof(remote_addr));

remote_addr.sin_family = AF_INET;

remote_addr.sin_addr.s_addr = inet_addr(“127.0.0.1”);

remote_addr.sin_port = htons(8000);

if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0)

{

printf(“Error\n”);

return -1;

}

if( connect(s, (struct sockaddr*)&remote_addr, sizeof(struct sockaddr)) < 0 )

{

printf(“Error\n”);

return -1;

}

printf(“Connection established\n”);

len = recv(s, buf, BUFSIZ, 0);

buf[len] = ”;

printf(“%s\n”, buf);

while(1)

{

printf(“Enter text: “);

scanf(“%s%”, buf);

if( !strcmp(buf, “quit”) )

break;

len = send(s, buf, strlen(buf), 0);

len = recv(s, buf, BUFSIZ, 0);

buf[len] = ”;

printf(“From server: %s\n”, buf);

}

close(s);

return 0;

}

TCP CLIENT

 
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string.h>
 
int main(void)
{
        char buf[BUFSIZ], ubuf[BUFSIZ];
        int s, fd, len;
        int sin_size;
        struct sockaddr_in my_addr;
        struct sockaddr_in remote_addr;
 
        memset(&my_addr, 0, sizeof(my_addr));
        my_addr.sin_family = AF_INET;
        my_addr.sin_addr.s_addr = INADDR_ANY;
        my_addr.sin_port = htons(8000);
 
        if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        {
               printf("Error\n");
               return -1;
        }
 
        if( bind(s, (struct sockaddr*)&my_addr, sizeof(struct sockaddr))  < 0)
        {
               printf("Error\n");
               return -1;
        }
 
        listen(s, 6);
 
        sin_size = sizeof(struct sockaddr_in);
        if( (fd = accept(s, (struct sockaddr*)&remote_addr, &sin_size)) < 0 )
        {
               buf[len] = '';
               buf[0] = toupper(buf[0]);
               send(fd, buf, len, 0);
        }
 
        close(fd);
        close(s);
        return 0;
}
Advertisements

2 thoughts on “TCP Server and Client

  1. helo sir we want vi semester 2007 regulation computer networks lab programs.
    we expect ur kind reply.

Comments are closed.