我正在使用UNIX套接字编写HTTP客户端(作为家庭作业的一部分)。我目前有这个工作代码连接到给定的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文档非常糟糕。
答案 0 :(得分:2)
你想要的可能是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地址。但是,它已经连接到相关主机。