我花了好几个小时来寻找问题的解决方法,当我写问题描述并且需要说明时,终于找到了解决方案。我把解决方案发布出来,希望能够帮助到其他人。
使用getaddrinfo函数,如果我尝试连接到我的服务器,按照很多网站以及getaddrinfo函数的手册里面提供的示例代码所述,做(我认为的)正确的操作,但它失败了,并显示“连接超时”的错误消息: (为了更加简洁明了,下面是简化后的代码)
使用getaddrinfo函数,如果我尝试连接到我的服务器,按照很多网站以及getaddrinfo函数的手册里面提供的示例代码所述,做(我认为的)正确的操作,但它失败了,并显示“连接超时”的错误消息: (为了更加简洁明了,下面是简化后的代码)
void connect_UsingGetAddrInfo_Wrong (std::string host, unsigned short int port, int& socketfd)
{
//simplified loops & error handling for concision
int x;
int domain = AF_INET; // IP_v4
int socketType = SOCK_STREAM; // Sequenced, reliable, connection-based byte streams.
addrinfo hints, *addr;
//fine-tune hints according to which socket you want to open
hints.ai_family = domain;
hints.ai_socktype = socketType;
hints.ai_protocol = 0; // no enum : possible value can be read in /etc/protocols
hints.ai_flags = AI_CANONNAME | AI_ALL | AI_ADDRCONFIG;
x = getaddrinfo(hostname, NULL, &hints, &addr);
//shall rather loop on addr linked list, but this is not the topic here.
socketfd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
x = connect(socketfd, addr->ai_addr, addr->ai_addrlen);
}
然而,使用gethostbyname方法我能够连接到同一服务器上的套接字。
void connect_UsingGetHostByName_Deprecated (std::string host, unsigned short int port, int& socketfd)
{
//simplified loops & error handling for concision
int x;
int domain = AF_INET; // IP_v4
int socketType = SOCK_STREAM; // Sequenced, reliable, connection-based byte streams.
struct hostent DNS, *r;
char buf[1024];
x = gethostbyname_r(hostname.c_str(), & DNS, buf, sizeof(buf), & r, & err));
socketfd = socket(domain, socketType, 0);
//server.
sockaddr_in server;
memset(&server, 0x00, sizeof(server));
server.sin_family=domain;
server.sin_port=htons(port);
memcpy(& server.sin_addr.s_addr, DNS.h_addr, (size_t) DNS.h_length);
x = connect(socketfd, (struct sockaddr *) & server, sizeof(server));
}
运行代码显示两个版本都正确获取了服务器的有效IP地址。但是第一个版本无法连接,会超时。为什么?
x
、domain
、socketType
、hostname
、fd
是从哪里来的? - Tormund Giantsbane