遗留代码有 gethostbyname
来获取主机的 IP 地址。转换地址的整数部分然后传递给 IcmpSendEcho
。
我正在用 getaddrinfo
替换这个过时的函数。
DWORD GetIPAddressInt(const char* pAddress)
{
PADDRINFOA addr = nullptr;
addrinfo hints = { 0 };
hints.ai_family = AF_INET;
// hints.ai_socktype = ??;
// hints.ai_protocol = ??;
getaddrinfo(pAddress, nullptr, &hints, &addr);
auto sockaddr_ipv4 = reinterpret_cast<sockaddr_in*>(addr->ai_addr);
return sockaddr_ipv4->sin_addr.S_un.S_addr;
}
我的问题是:ai_socktype
和 ai_protocol
成员呢?
- 套接字类型应该是
SOCK_RAW
吗? - 协议(protocol)应该是
IPPROTO_ICMP
(在 header 中,而不是在 MSDN 中)吗?
再次重申,得到的IP地址将用于发送ICMP回显请求,因此我想知道是否需要RAW/ICMP?目前,IPv6 不是问题。
最佳答案
关于 getaddrinfo 的文档,您可以将此字段留空 (0)。
A value of zero for ai_socktype indicates the caller will accept any socket type.
A value of zero for ai_protocol indicates the caller will accept any protocol.
IPv4 和 IPv6 地址不取决于是用于流还是特定协议(protocol)类型。因此调用 IcmpSendEcho
时只需忽略此字段即可。
编辑:
套接字类型和协议(protocol)提示可能仅在指定服务名称时才相关。服务名称可以是“http”、“tftp”等。例如,如果指定“tftp”服务,则不能设置“stream”套接字类型,因为 tftp 是基于数据报的。但在您的情况下(也可能是大多数其他时间),服务字段保留为 NULL。例如,如果指定“http”服务,则ai_addr.sin_port 中的端口成员也应填写。
关于c++ - 将 gethostbyname 替换为 ICMP 的 getaddrinfo (IcmpSendEcho),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089050/