我正在尝试实现一个名为“inet_pton”的函数,它将 IPv4 或 IPv6 的字符串表示(如“66.102.1.147”[google])转换为二进制网络字节有序形式。这是我的代码的相关部分:
#if defined WIN32
int inet_pton (int af, const char *src, void *dst)
{
const void *data;
size_t len;
struct addrinfo hints, *res;
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_NUMERICHOST;
if (getaddrinfo (src, NULL, &hints, &res))
{
std::cout << "ERROR : inet_pton() in " << __FILE__ << " at line " << __LINE__ << std::endl;
std::cout << " : getaddrinfo() failed to get IP address info for \"" << src << "\"" << std::endl;
return 0;
}
...
所以 src 是传入的 IP 字符串。但是,我总是收到类似的错误
getaddrinfo() 无法获取“66.102.1.147”的 IP 地址信息
有winsock经验的人可以评论吗?我还尝试了另一种方法,函数
WSAStringToAddress ((LPTSTR)src, af, NULL, (LPSOCKADDR) &sa, &address_length)
但它总是返回错误代码 WSAEINVAL,表示 IP 字符串无效。这对我来说毫无意义。我使用 VS2005 作为我的 IDE。