Sei sulla pagina 1di 4

EX.NO: 7 DATE: 26.08.

2010

TCP CLIENT/SERVER AIM:


To write Unix program for implementing the TCP client/server.

ALGORITHM:
STEP 1: Start the program STEP 2: For server create a socket and initialize the family STEP 3: Listen for the client request by using listen() method STEP 4: To Accept the clients connection request using the accept method STEP 5: Read the message send by the client using read() method STEP 6: Reply to the client message by writing it using the write() method STEP 7: Close the file descriptor STEP 8: For client create a socket and initialize the family STEP 9: Send connect request to the server using the connect() method STEP 10: To accept the clients connection request using the accept method STEP 11: Send message to the server by writing it using the write() method STEP 12: Read the message send by the server using read() method STEP 13: Stop the process

PROGRAM:
//tcpserver.c # include <stdio.h> #include<string.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # define PORT 1235 int main() { int listenfd,connfd; socklen_t len; pid_t c_pid; struct sockaddr_in server,client; char buff[100]; listenfd=socket(AF_INET,SOCK_STREAM,0); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_addr.s_addr=htonl(INADDR_ANY); server.sin_port=htons(PORT); bind(listenfd,(struct sockaddr*)&server,sizeof(server)); listen(listenfd,10); printf("SERVER:\n"); while(1) { len=sizeof(client); connfd=accept(listenfd,(struct sockaddr*)&client,&len); c_pid=fork(); if(c_pid==0) { close(listenfd); read( connfd,buff,sizeof(buff)); printf("\nReceived >%s ",buff); printf("\nSend > "); scanf("%s",buff); write(connfd,buff,sizeof(buff)); exit(0); } close(connfd); }

} //tcpclient.c #include<netinet/in.h> #include<string.h> #include<stdio.h> #define PORT 1235 int main(int argc, char **argv) { int sockfd,n; socklen_t len; struct sockaddr_in server; char buff[100]; printf("CLIENT:\n"); while(1) { sockfd=socket(AF_INET,SOCK_STREAM,0); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(PORT); connect(sockfd,(struct sockaddr*)&server,sizeof(server)); printf("\nSend > "); scanf("%s",buff); write(sockfd,buff,sizeof(buff)); read(sockfd,buff,sizeof(buff)); printf("Received > %s",buff); } }

OUTPUT:

Client: [IIMCA159@CALINUX ~]$ ./tcpser.out SERVER: Received >hi Send > welcome Received >thankyou Send > hai Received >hi.. Send > unix Received >test Server: [IIMCA159@CALINUX ~]$ ./tcpcli.out CLIENT: Send > hi Received > welcome Send > thankyou Received > hai Send > hi.. Received > unix Send > test

RESULT: Thus the Unix program for implementing the TCP client/server has been executed successfully.

Potrebbero piacerti anche