forked from DingHe/unpv13e
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tcp_connect.c
51 lines (40 loc) · 1.38 KB
/
tcp_connect.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
/* include tcp_connect */
#include "unp.h"
int
tcp_connect(const char *host, const char *serv)
{
int sockfd, n;
struct addrinfo hints, *res, *ressave;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;//会首先搜索AAAA记录,然后搜索A记录
hints.ai_socktype = SOCK_STREAM;
if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0)
err_quit("tcp_connect error for %s, %s: %s",
host, serv, gai_strerror(n));
ressave = res;
//对于同时支持IPv4和IPv6的主机,由于设置了AF_UNSPEC,所以首先会搜索AAAA
//记录,连接成功后循环终止,可以通过指定带-4后缀的主机名来强制使用IPv4地址
do {
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd < 0)
continue; /* ignore this one */
if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
break; /* success */
Close(sockfd); /* ignore this one */
} while ( (res = res->ai_next) != NULL);
if (res == NULL) /* errno set from final connect() */
err_sys("tcp_connect error for %s, %s", host, serv);
freeaddrinfo(ressave);
return(sockfd);
}
/* end tcp_connect */
/*
* We place the wrapper function here, not in wraplib.c, because some
* XTI programs need to include wraplib.c, and it also defines
* a Tcp_connect() function.
*/
int
Tcp_connect(const char *host, const char *serv)
{
return(tcp_connect(host, serv));
}