gpt4 book ai didi

c - InetPtonW 始终返回 1.0.0.0

转载 作者:行者123 更新时间:2023-11-30 20:17:21 25 4
gpt4 key购买 nike

我刚刚开始学习C,现在正在学习如何使用winsock2-Header。要将 IP 地址从字符串表示形式转换为二进制形式,我使用函数 InetPtonW。我的问题是这个函数总是返回 IP 地址 1.0.0.0。

我在 Windows 10 上使用 Visual Studio。我阅读了 Microsoft 的文档(请参阅 here ),并且还阅读了 this关于 Stackoverflow 的问题。我使用其他数据类型尝试了不同的方法,但无法得到正确的结果。

下面是我的问题的相关代码。

int main() {
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
PCWSTR pStringIp = (L"172.217.168.14"); //IP for own webserver
PVOID pAddrBuf;
char* message;
char* recvbuf; // Buffer for the reply
int recvbuflen = DEFAULT_BUFLEN; //Size of the reply from the server
/* Socket creation etc. would be here */
pAddrBuf = malloc(INET6_ADDRSTRLEN);
if (pAddrBuf == NULL) {
printMemoryErrorFailMessage(errno, pAddrBuf);
return EXIT_FAILURE;
}
server.sin_addr.s_addr = InetPtonW(AF_INET, pStringIp, pAddrBuf);
free(pAddrBuf);
}

我希望在示例中 IP 地址将转换为 172.217.168.14,而不是 1.0.0.0

如果您需要更多信息或更多代码,请询问。感谢您的帮助。

请Necessary_Function

最佳答案

来自the InetPtonW documentation :

  • 对于参数pAddrBuf

    A pointer to a buffer in which to store the numeric binary representation of the IP address. The IP address is returned in network byte order.

  • 对于返回值

    If no error occurs, the InetPton function returns a value of 1 and the buffer pointed to by the pAddrBuf parameter contains the binary numeric IP address in network byte order.

总结一下:该函数根据成功还是失败返回 bool 值 10;如果成功,它将地址写入 pAddrBuffer(第三个参数)指向的内存中。

之所以得到地址1.0.0.0是因为你使用返回的 bool 结果作为地址,而丢弃了写入pAddrBuf<指向的内存的实际地址.

使用该函数的“正确”方法如下:

if (InetPtonW(AF_INET, pStringIp, &server.sin_addr.s_addr) == 1)
{
// Success, use the address some way
}

关于c - InetPtonW 始终返回 1.0.0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969791/

25 4 0
文章推荐: javascript - 将多个数据数组附加到数据点
文章推荐: javascript - 在 react 中显示/隐藏特定的
文章推荐: C初学者关于文件
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com