-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathdaytimed.c
92 lines (82 loc) · 2.14 KB
/
daytimed.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
81
82
83
84
85
86
87
88
89
90
91
92
/*
daytimed.c -- Simple daytime server.
Copyright (c) 2017 Minero Aoki
This program is free software.
Redistribution and use in source and binary forms,
with or without modification, are permitted.
*/
#if defined(__digital__) && defined(__unix__)
# ifdef _XOPEN_SOURCE
# undef _XOPEN_SOURCE
# endif
# define _XOPEN_SOURCE 500
# define _OSF_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define DEFAULT_PORT 13
static int listen_socket(int port);
int
main(int argc, char *argv[])
{
struct sockaddr_storage addr;
socklen_t addrlen = sizeof addr;
int sock, server;
time_t t;
struct tm *tm;
char *timestr;
server = listen_socket(argc > 1 ? atoi(argv[1]) : DEFAULT_PORT);
sock = accept(server, (struct sockaddr*)&addr, &addrlen);
if (sock < 0) {
perror("accept(2)");
exit(1);
}
time(&t);
tm = localtime(&t);
timestr = asctime(tm);
write(sock, timestr, strlen(timestr));
close(sock);
close(server);
exit(0);
}
static int
listen_socket(int port)
{
struct addrinfo hints, *res, *ai;
int err;
char service[16];
memset(&hints, 0, sizeof(struct addrinfo));
/* hints.ai_family = AF_UNSPEC; */
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
snprintf(service, sizeof service, "%d", port);
if ((err = getaddrinfo(NULL, service, &hints, &res)) != 0) {
fprintf(stderr, "%s\n", gai_strerror(err));
exit(1);
}
for (ai = res; ai; ai = ai->ai_next) {
int sock;
sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (sock < 0) continue;
if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
close(sock);
continue;
}
if (listen(sock, 5) < 0) {
close(sock);
continue;
}
freeaddrinfo(res);
fprintf(stderr, "listening on port %d...\n", port);
return sock;
}
fprintf(stderr, "cannot listen socket\n");
exit(1);
}