Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inet_pton with all zero ip address

I am using inet_pton to verify if the input IP address is valid and is not all zeros ( 0.0.0.0 or 00.00.0.0).

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

If the input ip (src) address is 0.0.0.0 inet_pton set dst to value 0. If src value is 00.00.00.00 , dst value is not 0, but I get a random value for each trail. Why inet_pton convert 0.00.00.00 to value 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);
}

Sample Runs

Correct values:

./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

Incorrect results:

./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**
like image 917
Joy Avatar asked Mar 23 '23 16:03

Joy


2 Answers

You're not checking if inet_pton() returns 0. The man page of inet_pton states:

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

Try something like:

#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;
    } 
}
like image 139
djf Avatar answered Apr 06 '23 09:04

djf


When in doubt read the documentation.

man inet_pton on my Linux box tells me that your error return check is wrong. It returns 1 on success. Anything else is an error. 0 means an invalid conversion. -1 means an invalid address family.

like image 30
Zan Lynx Avatar answered Apr 06 '23 09:04

Zan Lynx