-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcpserv.c
52 lines (39 loc) · 1.31 KB
/
tcpserv.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
#include <sys/socket.h>
#include <netinet/in.h>
#define SERV_PORT 23456
void process(int sockfd);
int main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
listen(listenfd, 5);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
if ( (childpid = fork()) == 0) { /* child process */
close(listenfd); /* close listening socket */
process(connfd); /* process the request */
exit(0);
}
close(connfd); /* parent closes connected socket */
}
}
void process(int sockfd)
{
ssize_t n;
char buffer1[80], buffer2[]="Thanks for calling...";
for ( ; ; ) {
if ( (n = recv(sockfd, buffer1, sizeof(buffer1),0)) == 0)
return; /* connection closed by other end */
printf ("Server: Received %s", buffer1);
send(sockfd, buffer2, sizeof(buffer2),0);
}
}