The library function inet_aton can be used to extract IP address from a string format (eg: “123.23.42.76″). This function returns non-zero value if the IP address is valid and zero if it is an invalid IP address. The following example shows how to use this library function.

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

char *ips[] = {
   "12.34.56.7",
   "123.123.123.123",
   "255.255.255.255",
   "345.123.23.54",
   NULL
};

int main(int argc, char *argv[])
{
   int i;
   struct in_addr ia;

   i = 0;
   while(ips[i]) {
   if(inet_aton(ips[i],&ia) == 0) {
     printf("%s is an INVALID ip address\n", ips[i]);
   } else {
     printf("%s is a VALID ip address. 0x%lx\n", ips[i], ia.s_addr);
   }
   i++;
  }
}

The following will be output of the above example program.

[neo@techpulp ~]# gcc a2n.c -o a2n
[neo@techpulp ~]# ./a2n
12.34.56.7 is a VALID ip address. 0x738220c
123.123.123.123 is a VALID ip address. 0x7b7b7b7b
255.255.255.255 is a VALID ip address. 0xffffffff
345.123.23.54 is an INVALID ip address
[neo@techpulp ~]#