View Antoni Milton's profile on LinkedIn

Sunday, March 14, 2010

How to check the given string is valid IPAddress or Domain Name?

Using inet_pton function we can determine, whether given string is a valid IPv4/v6 Address or Domain name.

In below example,

first check the given string is a valid Ipv4 address not then check valid Ipv6 address and check the input string as a valid domain name.

int CheckIPAddress( const char* pszHostName)
{
int iResult =0; // 1 - Ipv4,2-Ipv6, 3- domain name, 0-invalid ip

struct sockaddr_in sockAddr;
struct in_addr addr;
struct in6_addr aadrv6;
struct hostent *host;
int iTemp = inet_pton(AF_INET, pszHostName, &(sockAddr.sin_addr));
if( iTemp == 1 ) // vaild IPv4 Address
{
iResult = 1;
}
else if( inet_pton(AF_INET6,pszHostName,&aadrv6 ) == 1)
{
iResult = 2;
}
else // may be a domain name. try convert in to Ipv4 Address
{
if (( host = gethostbyname( pszHostName )) != NULL )
{
addr.s_addr = *(u_long *) host->h_addr_list[0];
printf("IPAddress: %s\n", inet_ntoa( addr) );
iResult = 3;
}
}
return iResult;
}

No comments: