TCP Client.cpp
#include<stdio.h>
#include<sys/socket.h>
#include<iostream.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netbd.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<errno.h>
#define MAX 100
main(int argc.char*argv)
{
int sockfd,n;
char buff[100];
struct sockaddr_in serv;
if(argc!=3)
{
printf("\n Error ! usage:./a.out<IP ADDRESS><PORT>\n");
exit(0);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("\n Error ! Socket not created...\n");
exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(atoi9argv[2]));
if(inet_pton(AF_INET,argv[1],&serv.sin_addr)<0)
{
printf("\n Errorin conversion of IP address from string to num\n");
exit(0);
}
if(connect(sockfd,(struct sockaddr*)&serv,sizeof(serv))<0)
{
printf("\n Error ! can not established...\n");
exit (0);
}
printf("\n connected..\n");
strcpy(buff,"abc");
while(strcmp(buff,"bye")!=0)
{
cout<<"\n Client:";
gets(buff);
write(sockfd,buff,strlen(buff));
cout<<"\n Server:";
n=read(sockfd,buff,100);
buff[n]='\0';
cout<<buff;
if(n<0)
{
cout<<"\n Read Error";
exit (0);
}
}
cout<<"\n";
return 0;
}
TCP Server.cpp
#include<iostream.h>
#include<stdio.j>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<time.h>
int main()
{
int listenfd,connfd,n;
struct sockaddr_in serv;
char buff[100];
int port=1058;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_addr.s_addr=htonl(INADDR_ANY);
serv.sin_port=htons(port);
bind(listenfd,(struct sockaddr*)&serv,sizeof(serv));
listen(listenfd,15);
while(1)
{
connfd=accept(listenfd,(struct sockaddr*)NULL,NULL);
cout<<"\nConx.Open!]n";
int child;
if((child=fork())<0)
{
cout<<"\nChild disaster!";
exit(1);
}
else if(child==0)
{
close(listenfd);
strcpy(buff,"abc");
while(strcmp(buff,"bye")!=0)
{
if(strcmp(buff,"bye")==0) break;
n=read(connfd,buff,100);
buff[n]='\0';
cout<<"\nClient:"<<buff;
cout<<"Server:";
gets(buff);
write(connfd,buff,strlen(buff));
}
cout<<"\n\n Conx closed!";
close(connfd);
exit(0);
}
close(connfd);
}
return 0;
}
OUTPUT SCREEN:-
Server side:
[cseb58@localhost cseb58]$ TCPserver.cpp
[cseb58@localhost cseb58]$ ./a.out
conx open!
Client : hai server!
cliebt : bye
Client side:
[cseb58@localhost cseb58]$ TCPclient.cpp
[cseb58@localhost cseb58]$ ./a.out 127.0.0.1 1858
connected
server:hai
server:see you
No comments:
Post a Comment