时间服务器小例子

时间服务器小例子

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
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
using namespace std;

int main()
{
int serverSock = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in serverAddr;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(13);

bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
listen(serverSock, 5);
while (true)
{
struct sockaddr_in clientAddr;
socklen_t len = sizeof(clientAddr);
int clientSock = accept(serverSock, (struct sockaddr*)&clientAddr, &len);
char ipbuf[INET_ADDRSTRLEN];
printf("connection from %s, port %d\n",
inet_ntop(AF_INET, &clientAddr.sin_addr, ipbuf, sizeof(ipbuf)),
ntohs(clientAddr.sin_port));

time_t t = time(NULL);
char buf[1024];
snprintf(buf, 1024, "%.24s\r\n", ctime(&t));

write(clientSock, buf, strlen(buf));
close(clientSock);
}

return 0;
}

抄书copy了一下

Proudly powered by Hexo and Theme by Hacker
© 2021 wastecat