C 获取IP地址并使用套接字连接到该地址

C 获取IP地址并使用套接字连接到该地址,c,sockets,gethostbyname,C,Sockets,Gethostbyname,我正在使用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 t

我正在使用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);
}

我知道我做错了,但是gethostbyname文档太糟糕了。

您想要的可能是
getaddrinfo(3)

#包括 #包括 静态整数 解析(常量字符*主机,常量字符*端口) { 结构addrinfo*aires; 结构addrinfo提示={0}; int s=-1; hits.ai_family=AF_unsec; hits.ai_socktype=SOCK_流; hints.ai_flags=0; #如果定义了AI_ADDRCONFIG hits.ai_flags |=ai_ADDRCONFIG; #endif/*AI_ADDRCONFIG*/ #如果定义了AI_v4; hits.ai_flags |=ai_v4;; #endif/*AI_*/ hits.ai_协议=0; if(getaddrinfo(主机、端口、提示和艾利斯)<0){ 出去; } /*现在都试试*/ for(const struct addrinfo*ai=aires; 哎!=零&& ((s=socket(ai->ai_族,ai->ai_socktype,0))<0|| 连接(s,ai->ai地址,ai->ai地址)<0; 关闭(s),s=-1,ai=ai->ai\U下一步); 输出: 弗里亚德林福(艾利斯); 返回s; }
此版本从主机/端口对获取套接字。它还接受主机的IP地址和端口的服务字符串。但是,它将已经连接到有问题的主机。

memcpy(&address.sin\u addr,host\u entity->h\u addr\u list[0],host\u entity->h\u length)@BrianRoach就是他干的!如果你想写下来作为答案,我会接受的
struct hostent *host_entity = gethostbyname(server_address);
address.sin_addr.s_addr = host_entity->h_addr_list[0];
#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; }