TCP SOCKETS
Server :
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 2020
#define BACKLOG 2
main()
{
int fd,fd1,sin_addr,i=0;
char content[30];
struct sockaddr_in server;
struct sockaddr_in client;
int sin_size;
if((fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
{
printf("Socket()
error\n");
exit(-1);
}
bzero((char
*)&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(fd,(struct
sockaddr*)&server,sizeof(server))==-1)
{
printf("Bind()
error");
exit(-1);
}
if(listen(fd,BACKLOG)==-1)
{
printf("listen()
error\n");
exit(-1);
}
printf("\n The server is in
listening mode……\n");
sin_size=sizeof(client);
if((fd1=accept(fd,(struct sockaddr*)&client,&sin_size))==-1)
{
printf("accept()
error\n");
exit(-1);
}
i=0;
printf("Point to point
connection, type EXIT to quit……\n");
if(!fork())
while(1)
{
i=recv(fd1,content,30,0);
content[i]='\0';
printf("%s\n",content);
if(!strcmp(content,"EXIT"))
{
printf("Client
wants to close..");
break;
}
}
else
while(1)
{
scanf("%s",content);
send(fd1,content,30,0);
if(!strcmp(content,"EXIT"))
{
printf("Write
mode on exit..");
break;
}
}
close(fd);
close(fd1);
}
Client :
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 2020
main()
{
int fd1,i;
char content[30];
struct sockaddr_in client;
if((fd1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
{
printf("Socket()
error");
exit(-1);
}
bzero(&client,sizeof(client));
client.sin_family=AF_INET;
client.sin_port=htons(PORT);
if(connect(fd1,(struct
sockaddr*)&client,sizeof(client))==-1)
{
printf("connect()
error");
exit(-1);
}
printf("Point to point
communication , type EXIT to quit……\n");
i=0;
if(!fork())
while(1)
{
i=recv(fd1,content,30,0);
content[i]='\0';
printf("%s\n",content);
if(!strcmp(content,"EXIT"))
{
break;
}
}
else
while(1)
{
scanf("%s",content);
send(fd1,content,30,0);
if(!strcmp(content,"EXIT"))
{
printf("Write
mode on exit..");
break;
}
}
close(fd1);
}
OUTPUT:
Server side:
The server is in listening mode……
Point to point communication, Type
EXIT to quit……
Hai
Hello
Good
Morning
Client wants to close..
EXIT
Write mode on exit..
Client side:
Point to point communication, Type
EXIT to quit……
Hai
Hello
Good
Morning
EXIT
Write mode on exit..
No comments:
Post a Comment