c - ip地址全为零的inet_pton

标签 c linux network-programming

我正在使用 inet_pton 来验证输入的 IP 地址是否有效并且不全为零(0.0.0.0 或 00.00.0.0)。

inet_pton(int af, const char *src, void *dst)

如果输入 ip (src) 地址为 0.0.0.0 inet_pton 将 dst 设置为值 0。如果 src 值为 00.00.00.00 ,dst 值不为 0,但我为每条路径得到一个随机值。为什么 inet_pton 将 0.00.00.00 转换为值 0

#include <string.h>
#include <arpa/inet.h>

void main( int argc, char *argv[])
{
    int s;
    struct in_addr ipvalue;

    printf("converting %s to network address \n", argv[1]);
    s = inet_pton(AF_INET, argv[1], &ipvalue);

    if(s < 0)
            printf("inet_pton conversion error \n");

    printf("converted value = %x \n", ipvalue.s_addr);
}

样本运行

正确的值:

./a.out 10.1.2.3
converting 10.1.2.3 to network address
converted value = 302010a

./a.out 0.0.0.0
converting 0.0.0.0 to network address
converted value = 0

不正确的结果:

./a.out 00.00.00.0
converting 00.00.00.0 to network address
converted value = **a58396a0**

./a.out 00.0.0.0
converting 00.0.0.0 to network address
converted value = **919e2c30**

最佳答案

您没有检查 inet_pton() 是否返回 0。 man page of inet_pton状态:

inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT

尝试这样的事情:

#include <stdio.h>
#include <arpa/inet.h>


int main( int argc, char *argv[])
{
    int s;
    struct in_addr ipvalue;

    printf("converting %s to network address \n", argv[1]);
    s = inet_pton(AF_INET, argv[1], &ipvalue);

    switch(s) {
       case 1:
          printf("converted value = %x \n", ipvalue.s_addr);
          return 0;
       case 0:
          printf("invalid input: %s\n", argv[1]);
          return 1;
       default:
          printf("inet_pton conversion error \n");
          return 1;
    } 
}

关于c - ip地址全为零的inet_pton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16971518/

相关文章:

CULA 中的 culagesvd()

Clion:条件编译标志

c - f(x) := if x == 0 then 0 else (x * log(x)) 的无分支实现

linux - $ * * * * * echo "hi"=> blado.kdb : command not found

vb.net - .NET套接字发送和接收不匹配

c - 为什么不能将 C 标准 I/O 与套接字一起使用

c - 看似不可能的错误检查

linux - MATLAB Linux 内存不足错误

c - 使用事件驱动套接字时如何生成网络事件 FD_WRITE?

linux - Raspberry Pi USB 安装错误(sd* 字母总是变化)