-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverint.c
80 lines (79 loc) · 1.76 KB
/
serverint.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
78
79
80
#include"myheaders.h"
void client_info(int ,struct sockaddr_in );
int main(int argc,char **argv)
{
if(argc<2)
{
puts("input format:server_exe well_known port_no");
return;
}
int sfd;
puts("creating server socket");
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{perror("socket");return;
}
puts("server socket created");
struct sockaddr_in saddr;
int slen=sizeof(saddr);
puts("binding...");
saddr.sin_family=AF_INET;
saddr.sin_port=atoi(argv[1]);
saddr.sin_addr.s_addr=inet_addr("0.0.0.0");
if(bind(sfd,(const struct sockaddr *)&saddr,slen)<0)
{perror("bind");close(sfd);return;}
puts("bind success");
puts("creating connections queue for only 1");
if(listen(sfd,1)<0)
{
perror("listen");close(sfd);return;}
puts("connection queue created");
struct sockaddr_in caddr;
int clen=sizeof(caddr),newfd;
puts("waiting passively for connection from any client");
newfd=accept(sfd,(struct sockaddr *)&caddr,&clen);
if(newfd<0)
{perror("accept");close(sfd);return;}
puts("connection with client");
client_info(newfd,caddr);
int buff;int status;
puts("waiting for message from client");
status=recv(newfd,&buff,4,0);
if(status<0)
{perror("recv");}
else if(status==0)
{puts("client abruptly terminated");
}
else
{
printf("server received:%d\n",buff);
printf("server echoes\n");
}
int n,rev=0;
n=buff;
while(n)
{
rev*=10;
rev+=n%10;
n=n/10;
}
printf("%d",rev);
status=send(newfd,&rev,4,0);
if(status<0)
{perror("send");}
/*if(strcmp(buff,"quit")==0)
{
puts("client formally terminating connection with server");
}*/
close(newfd);
close(sfd);
}
void client_info(int newfd,struct sockaddr_in caddr)
{
puts("whose");
char *p=inet_ntoa(caddr.sin_addr);
unsigned short portno=ntohs(caddr.sin_port);
printf("ip address is :%s\n",p);
printf("ephemeral port is :%d\n",portno);
printf("file descriptor is:%d\n",newfd);
}