获取地址IP并使用套接字连接到它
问题描述:
我正在使用UNIX套接字(作为家庭作业的一部分)编写HTTP客户端。目前,我有这方面的工作代码连接到指定的IP地址:获取地址IP并使用套接字连接到它
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
char *server_address = "127.0.0.1";
struct sockaddr_in address;
if (sockfd < 0) {
printf("Unable to open socket\n");
exit(1);
}
// Try to connect to server_address on port PORT
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(server_address);
address.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr*) &address, sizeof(address)) < 0) {
printf("Unable to connect to host\n");
exit(1);
}
不过,我现在想修改它,以便server_address
也可能是东西是不是一个IP,如“google.com”。我一直在试图找出如何使用gethostbyname
来做到这一点,但我遇到了麻烦。
gethostbyname会同时接受IP地址或像“google.com”这样的地址并使其正常工作吗?(或者我应该先尝试在地址上运行一个正则表达式,如果它是IP地址,则执行其他操作)?
我曾尝试下面的代码,试图把它的东西,如“google.com”的工作,但我得到一个警告warning: assignment makes integer from pointer without a cast
struct hostent *host_entity = gethostbyname(server_address);
address.sin_addr.s_addr = host_entity->h_addr_list[0];
我知道我这样做,它-错,但gethostbyname文档是非常残酷的。
答
你想要的是也许getaddrinfo(3)
:
#include #include static int resolve(const char *host, const char *port) { struct addrinfo *aires; struct addrinfo hints = {0}; int s = -1; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = 0; #if defined AI_ADDRCONFIG hints.ai_flags |= AI_ADDRCONFIG; #endif /* AI_ADDRCONFIG */ #if defined AI_V4MAPPED hints.ai_flags |= AI_V4MAPPED; #endif /* AI_V4MAPPED */ hints.ai_protocol = 0; if (getaddrinfo(host, port, &hints, &aires) < 0) { goto out; } /* now try them all */ for (const struct addrinfo *ai = aires; ai != NULL && ((s = socket(ai->ai_family, ai->ai_socktype, 0)) < 0 || connect(s, ai->ai_addr, ai->ai_addrlen) < 0); close(s), s = -1, ai = ai->ai_next); out: freeaddrinfo(aires); return s; }
这个版本让你从一个主机/端口对插槽。它还将主机和服务字符串的IP地址用于端口。但是,它已经连接到有问题的主机。
'的#include'' –
ugoren
2013-02-22 06:21:55
memcpy的(&address.sin_addr,host_entity-> h_addr_list [0],host_entity->长度h_length);' – 2013-02-22 06:21:55
@BrianRoach该做到了!如果你想把它写成答案,我会接受它。 :) – Darthfett 2013-02-24 18:42:59