c – 具有全零IP地址的inet_pton

我使用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 - 代码日志