-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy path16-19.c
65 lines (57 loc) · 1.57 KB
/
16-19.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
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include "apue.h"
#define BUFLEN 128
#define TIMEOUT 10
void sigalrm(int signo) {}
void print_uptime(int sockfd, struct addrinfo *aip) {
int n;
char buf[BUFLEN];
buf[0] = 0;
if (sendto(sockfd, buf, 1, 0, aip->ai_addr, aip->ai_addrlen) < 0) {
err_sys("sendto error");
}
alarm(TIMEOUT);
if ((n = recvfrom(sockfd, buf, BUFLEN, 0, NULL, NULL)) < 0) {
if (errno != EINTR) {
alarm(0);
}
err_sys("recv error");
}
alarm(0);
write(STDOUT_FILENO, buf, n);
}
int main(int argc, char *argv[]) {
struct addrinfo *ailist, *aip;
struct addrinfo hint;
int sockfd, err;
struct sigaction sa;
if (argc != 2) {
err_quit("usage: ruptime hostname");
}
sa.sa_handler = sigalrm;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGALRM, &sa, NULL) < 0) {
err_sys("sigaction error");
}
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_DGRAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0) {
err_quit("getaddrinfo error: %s", gai_strerror(err));
}
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
if ((sockfd = socket(aip->ai_family, SOCK_DGRAM, 0)) < 0) {
err = errno;
} else {
print_uptime(sockfd, aip);
exit(0);
}
}
fprintf(stderr, "can't contact %s: %s\n", argv[1], strerror(err));
exit(1);
}