C语言 使用 inet_ntop() 和 inet_pton() 转换 IP 地址输入(C 编程)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15465104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting IP Address input by using inet_ntop() & inet_pton() (C PROGRAMMING)
提问by A CSc Student----
i'm trying to convert an IP address that's inputted by a user so that I can perform some bitwise operations on it and a address already stored in a structure. My problem is however that when the IP address is converted back the output is always 255.255.255.255. For example a input of 10.0.0.1 or 192.16.2.1 always returns 255.255.255.255.
我正在尝试转换用户输入的 IP 地址,以便我可以对其执行一些按位运算以及已存储在结构中的地址。然而,我的问题是,当 IP 地址转换回时,输出始终为 255.255.255.255。例如,输入 10.0.0.1 或 192.16.2.1 总是返回 255.255.255.255。
Any help would be appreciated. THANKS
任何帮助,将不胜感激。谢谢
{
struct sockaddr_in sa;
char ipinput[INET_ADDRSTRLEN];
fputs("Enter an IP Address: ", stdout);
fflush(stdout);
fgets(ipinput, sizeof ipinput, stdin);
inet_pton(AF_INET, ipinput, &(sa.sin_addr));
inet_ntop(AF_INET, &(sa.sin_addr), ipinput, INET_ADDRSTRLEN);
printf("IP Address = \%s\ \n", ipinput);
}
回答by cnicutar
You're not checking the value returned by inet_pton, you would have noticed it fails. As it turns out, it doesn't like the newline left in by fgets. Trim it:
您没有检查 返回的值inet_pton,您会注意到它失败了。事实证明,它不喜欢fgets. 修剪它:
ipinput[strlen(ipinput) - 1] = 0;
回答by Md. Al Amin Bhuiyan
Try to follow this:
尝试遵循这一点:
inet_ntop(AF_INET, (void *)hent->h_addr_list[0],servIP,16);
inet_ntop(AF_INET, (void *)hent->h_addr_list[0],servIP,16);
inet_pton(AF_INET, hostIP, &(sa->sin_addr));

