-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
77 lines (71 loc) · 1.25 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<string.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<fcntl.h>
#include<sys/stat.h>
int main()
{
int s,r,recb,sntb,x;
printf("INPUT port number: ");
scanf("%d", &x);
struct sockaddr_in server;
char buff[50],buff2[50];
s=socket(AF_INET,SOCK_STREAM,0);
if(s==-1)
{
printf("\nSocket creation error.");
exit(0);
}
printf("\nSocket created.");
server.sin_family=AF_INET;
server.sin_port=htons(x);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
r=connect(s,(struct sockaddr*)&server,sizeof(server));
if(r==-1)
{
printf("\nConnection error.");
exit(0);
}
printf("\nSocket connected.");
printf("\n\n");
int pid;
pid=fork();
while(1){
if(pid>0)
{
//parent
recb=recv(s,buff,sizeof(buff),0);
if(recb==-1)
{
printf("\nMessage Recieving Failed");
close(s);
exit(0);
}
if(strcmp(buff,"BYE")==0)
break;
printf("\nParent - Message Recieved: ");
printf("%s\n", buff);
}
else
{
//child
printf("\nChild - Type Message: ");
scanf("%s", buff2);
sntb=send(s,buff2,sizeof(buff2),0);
if(sntb==-1)
{
close(s);
printf("\nMessage Sending Failed");
exit(0);
}
if(strcmp(buff2,"BYE")==0)
break;
}
}
close(s);
}