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**
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With