Inet_pton with all null ip address

I use inet_pton to verify that the input IP address is correct and not all zeros (0.0.0.0 or 00.00.0.0).

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

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

Run Examples

Valid 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** 
+4
source share
2 answers

You are not checking to see if inet_pton() 0 is returned. The inet_pton() man page states:

inet_pton () returns 1 on success (the network address was successfully Translated). 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; } } 
+6
source

If in doubt, read the documentation.

man inet_pton on my Linux box tells me that the error checking error is incorrect. It returns 1 for success. Everything else is a mistake. 0 means invalid conversion. -1 means an invalid address family.

+1
source

Source: https://habr.com/ru/post/1484912/


All Articles