-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathTCPDaytimeClientUseGetAddrInfo.c
65 lines (56 loc) · 1.52 KB
/
TCPDaytimeClientUseGetAddrInfo.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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char const *argv[])
{
if (argc != 3) {
printf("usage : %s <ip/hostname> <port/service>\n", argv[0]);
exit(1);
}
const char *hostname = argv[1];
const char *service = argv[2];
struct addrinfo hints, *res = NULL, *ressave = NULL;
bzero(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int error = 0;
if ((error = getaddrinfo(hostname, service, &hints, &res)) != 0) {
printf("getaddrinfo error! %s %s : %s\n", hostname, service, gai_strerror(error));
exit(1);
}
ressave = res;
int fd = -1;
do {
if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) {
perror("socket error!");
continue;
}
if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
perror("connect error!");
close(fd);
fd = -1;
continue;
}
break;
} while ((res = res->ai_next) != NULL);
if (res == NULL) {
printf("connect to %s %s fail!\n", hostname, service);
exit(1);
}
char buf[1024];
ssize_t nread = 0;
while ((nread = read(fd, buf, sizeof(buf))) > 0) {
buf[nread] = 0;
printf("%s", buf);
}
if (nread == 0)
printf("\n");
else
perror("read error!");
close(fd);
return 0;
}