I have made a simple socket program so that client can connect to server by specifying ip of system in which server is running.
And in server we can type characters which will be received by client and client will store it in a file.
I want to clear some doubts
in server.c it shows ip address of client properly and it gives ip address of server as 0.0.0.0 . Why it is so?
How should I modify the server , so that it can have multiple clients simultaneously.
client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include<stdlib.h>
#define PORT 2080
main(int argc,char *argv[])
{
int sock1;
sock1 = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serv;
serv.sin_port = htons(PORT);
//printf("%x %x\n",PORT,htons(PORT));
printf("%d ",argc);
serv.sin_family = AF_INET;
if(argc>1)
serv.sin_addr.s_addr = inet_addr(argv[1]);
else
{
printf("Plese enter a valid ip\n");
return 1;
}
printf("client connecting\n");
if(connect(sock1, (struct sockaddr *)&serv,sizeof(serv))==-1)
{
printf("Failed to connect\n");
exit(1);
}
else
printf("Server connection established\n");
char buf[50];
int i=0;
FILE* fp = fopen("client.txt","w");
while(1)
{
//printf("%d ",i);
char c;
//bzero(buf,sizeof(buf));
read(sock1,&c,1);
if(c=='`')
break;
//if(c!='\n')
printf("%c",c);
fprintf(fp,"%c",c);
//i++;
}
fclose(fp);
close(sock1);
}
server.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include<stdlib.h>
#define PORT 2080
main()
{
int sock1,sock2, clength;
FILE *ptr;
char c;
char ip[40];
sock1 = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serv,cli;
printf("Waiting for client\n");
serv.sin_family = AF_INET;
serv.sin_port = htons(PORT);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sock1,(struct sockaddr *)&serv, sizeof(serv));
listen(sock1,5);
clength = sizeof(cli);
sock2 = accept(sock1,(struct sockaddr *)&cli,&clength);
printf("\n Client Connected\n");
inet_ntop(AF_INET,(void *)&(cli.sin_addr),ip,clength);
printf("\nClient IP :%s ",ip);
inet_ntop(AF_INET,(void *)&(serv.sin_addr),ip,sizeof(serv));
printf("\nServer IP :%s ",ip);
while(1)
{
printf("\nEnter char : ");
scanf("%c",&c);
printf("%c",c);
write(sock2,&c,1);
if(c=='`')
break;
}
close(sock2);
close(sock1);
return 0;
}