#include<stdio.h> //printf,scanf fun
#include<string.h> //bzero fun
//#include<sys/types.h>
#include<sys/socket.h> //socket,connect,bind,listen,accept,read,write fun
#include<netinet/in.h> //socket address structure,htons,htonl fun
#include<arpa/inet.h> //pton,ntop,aton,ntoa fun
//#include<errno.h>
#define tcpport 7137
#define ipaddr "192.168.0.2"
int main()
{
int length;
int sockfd,clientfd,count=0;
struct sockaddr_in server,client;
char buffer[100];
sockfd=socket(AF_INET,SOCK_STREAM,0); // non negative value if ok, -1 on error
if(sockfd==-1)
{
perror("Error in creating the socket - server");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(tcpport);
if(inet_pton(AF_INET,ipaddr,&server.sin_addr)<0) // 0 if ok, -1 on error
{
perror("Error in address conversion");
close(sockfd);
exit(1);
}
if(bind(sockfd,(struct sockaddr *)&server,sizeof(server))<0) // 0 if ok, -1 on error
{
perror("Error in binding");
close(sockfd);
exit(1);
}
if(listen(sockfd,1)<0) // 0 if ok, -1 on error
{
perror("Error in listen");
close(sockfd);
exit(1);
}
length=sizeof(client);
clientfd=(accept(sockfd,(struct sockaddr *)&client, &length)); // non negative value if ok, -1 on error
if(clientfd==-1)
{
perror("Error in accept");
close(sockfd);
exit(1);
}
while(1)
{
if(read(clientfd,buffer,sizeof(buffer))<0) // no of bytes read from socket if ok, -1 on error
{
perror("Error in read of buffer");
close(sockfd);
exit(1);
}
printf("\n per1:\t %s",buffer);
printf("\nper2 : ");
gets(buffer);
if(write(clientfd,buffer,sizeof(buffer))<0)
{
perror("error");
close(sockfd);
exit(1);
}
printf("enetr");
if(strcmp(buffer,"bye")==0)
break;
}
close(sockfd); // 0 if ok, -1 on error
}