-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTCPserver.c
59 lines (45 loc) · 1.23 KB
/
TCPserver.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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
char buf[10];
int s, n, ns, len;
struct sockaddr_in name;
unsigned int portNum; //time in seconds
switch(argc) {
case 2:
portNum = atoi(argv[1]);
break;
default:
printf("Usage: %s [port_num]\n",argv[0]);
exit(-1);
}
/* Create the socket. */
s = socket(AF_INET, SOCK_STREAM, 0);
/* Create the address of the server. */
name.sin_family = AF_INET;
name.sin_port = htons(portNum);
name.sin_addr.s_addr = htonl(INADDR_ANY); /* Use the wildcard address.*/
len = sizeof(struct sockaddr_in);
/* Bind the socket to the address. */
bind(s, (struct sockaddr *) &name, len);
for(;;)
{
/* Listen for connections. */
listen(s, 10);
/* Accept a connection. */
ns = accept(s, (struct sockaddr *) &name, &len);
/* Read from the socket until end-of-file and
* print what we get on the standard output. */
// printf("Connection from : %s\n",inet_ntoa(name.sin_addr));
while ((n = recv(ns, buf, sizeof(buf), 0)) > 0)
write(1, buf, n);
close(ns);
}
close(s);
exit(0);
}