Thursday, May 10, 2012

Program to validate hostname and IPV4 address

Here we will see how to validate a given IPV4 address or given hostname. In the last post (IPV4 address format validation), we have seen different IPV4 address format. We will verify all those formats practically here.

Lets have a quick glance on the functions used in this program.

getaddrinfo(), function returns addresses associated with the given IP address or hostname. If this function returns error means that the input address is not in a valid IPV4 format or the host name is not resolved. The following program is based on this output. It is written and tested on Linux.

freeaddrinfo() function used to free the address structure returned by getaddrinfo.
gai_strerror() function used to get the error string for the error returned by getaddrinfo().

/* IPV4 and hostname validation */
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/*Validate IPV4 or hostname function */
int validateIPV4Addr(char *addr)
    int rc=0;
    struct addrinfo hints;
    struct addrinfo *result=NULL, *rp=NULL;
    int s;

   /* Obtain address(es) matching host */
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
    hints.ai_flags = 0;
    hints.ai_protocol = 0;          /* Any protocol */

   s = getaddrinfo(addr, NULL, &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
    } else {

  for (rp = result; rp != NULL; rp = rp->ai_next) {
     struct sockaddr_in *a=(struct sockaddr_in *)rp->ai_addr;


  if( result != NULL )

  return rc;

main(int argc, char *argv[])
  int rc;

   if (argc < 2) {
        fprintf(stderr, "Usage: %s [ipv4|hostname]\n", argv[0]);

   if( rc!=0 ){
     fprintf(stderr,"IP address/hostname is invalid\n");

   fprintf(stdout,"IP address/hostname is valid\n");
   return 0;

The following cases shows output of the program on different formats of IPaddress and hostname validation. 

 ncooltips# ./validateip
Usage: ./validateip [ipv4|hostname]

 ncooltips# ./validateip 1
IP address/hostname is valid

 ncooltips# ./validateip 1.2
IP address/hostname is valid

 ncooltips# ./validateip 1.2.3
IP address/hostname is valid

 ncooltips# ./validateip
IP address/hostname is valid

 ncooltips# ./validateip
getaddrinfo: Name or service not known
IP address/hostname is invalid

 ncooltips# ./validateip localhost
IP address/hostname is valid

 ncooltips# ./validateip localhostnotvalid
getaddrinfo: Name or service not known
IP address/hostname is invalid

Pin It
Related Posts Plugin for WordPress, Blogger...