25

What would be a good way to determine if a string contains an IPv4 address? Should I use isdigit()?

enveeed
  • 177
  • 2
  • 7

15 Answers15

58

I asked a similar question for C++. You should be able to use a slightly modified (for C) version of what I came up with back then.

bool isValidIpAddress(char *ipAddress)
{
    struct sockaddr_in sa;
    int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
    return result != 0;
}

You'll need to #include <arpa/inet.h> to use the inet_pton() function.

Update based on comments to the question: If you want to know if a C-style string contains an IP address, then you should combine the two answers given so far. Use a regular expression to find patterns that roughly match an IP address, then use the function above to check the match to see if it's the real deal.

zawata
  • 172
  • 6
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
  • The code above will reject the string if "localhost" is passed into it – Nehal J Wani Apr 01 '13 at 19:23
  • 6
    @NehalJ.Wani "localhost" is a hostname, not an IP address. – Bill the Lizard Apr 01 '13 at 20:13
  • 2
    Warning: this answer is not IPv6 compatible ! – aberaud Apr 02 '14 at 16:57
  • Or use #include – Thiago Falcao Oct 27 '16 at 20:17
  • @aberaud, Mike should been specify that him interested in both protocol versions. – isnullxbh Jan 21 '17 at 13:42
  • The selected answer for a c problem is c++? What are you doing? – Deanie Oct 19 '17 at 18:35
  • 2
    `inet_pton` may return `-1` upon error. Your test should be `result == 1` or at least `result > 0` – Shloim Nov 30 '17 at 19:18
  • @Shloim `inet_pton()` returns 0 if the input isn't a valid IP address, so `!= 0` is what's needed here. If someone needs more information from the return value, they should probably just be calling `inet_pton` directly instead of wrapping it in a function. – Bill the Lizard Nov 30 '17 at 19:51
  • It should be compared with 1 for extra caution: `If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT.` – Shloim Dec 03 '17 at 18:22
  • 2
    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. – KaKa May 23 '18 at 01:38
  • Unlike inet_aton() and inet_addr(), inet_pton() accepts only IPv4 addresses in dotted-decimal notation. So it's better choice to use inet_pton() – 翟桂锋 Dec 17 '19 at 11:13
9

This is a routine I wrote a while ago for an embedded system which generated various suspect patterns on a network. As such, it uses absolutely no fancy stuff like network libraries or even the standard C libraries, preferring to steer clear of all that modern stuff like string tokenizing and (shudder) regular expression libraries :-) To that end, it's suited to just about any environment you could find yourself in, and it was blindingly fast.

Although, if you're in an environment that has something like checkIp4Addess(), I'd suggest you use that instead. It's an indication of the stuff you sometimes have to put up with when doing embedded stuff (although it is a real solution).

int isValidIp4 (char *str) {
    int segs = 0;   /* Segment count. */
    int chcnt = 0;  /* Character count within segment. */
    int accum = 0;  /* Accumulator for segment. */

    /* Catch NULL pointer. */

    if (str == NULL)
        return 0;

    /* Process every character in string. */

    while (*str != '\0') {
        /* Segment changeover. */

        if (*str == '.') {
            /* Must have some digits in segment. */

            if (chcnt == 0)
                return 0;

            /* Limit number of segments. */

            if (++segs == 4)
                return 0;

            /* Reset segment values and restart loop. */

            chcnt = accum = 0;
            str++;
            continue;
        }
        /* Check numeric. */

        if ((*str < '0') || (*str > '9'))
            return 0;

        /* Accumulate and check segment. */

        if ((accum = accum * 10 + *str - '0') > 255)
            return 0;

        /* Advance other segment specific stuff and continue loop. */

        chcnt++;
        str++;
    }

    /* Check enough segments and enough characters in last segment. */

    if (segs != 3)
        return 0;

    if (chcnt == 0)
        return 0;

    /* Address okay. */

    return 1;
}
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
  • 2
    That's a good point - I think we put that in to stop things like 192.1.004.1. Either that client's been very lucky or they stopped using our code due to bugs :-). I'll fix it. – paxdiablo Apr 28 '09 at 05:52
  • `if ((chcnt > 0) && (accum == 0)) return 0;` before `/* Accumulate and check segment. */` would prevent leading zeros like 01. – Vladimir Gamalyan Aug 01 '19 at 05:41
3
int validateIP4Dotted(const char *s)
{
    int len = strlen(s);

    if (len < 7 || len > 15)
        return 0;

    char tail[16];
    tail[0] = 0;

    unsigned int d[4];
    int c = sscanf(s, "%3u.%3u.%3u.%3u%s", &d[0], &d[1], &d[2], &d[3], tail);

    if (c != 4 || tail[0])
        return 0;

    for (int i = 0; i < 4; i++)
        if (d[i] > 255)
            return 0;

    return 1;
}
masoud
  • 51,434
  • 14
  • 119
  • 190
1

This is my try with a very low level C programming ( actually used in one of my programs for a PIC microcontroller). It does not use of string.h library. It does not use pointers, as this compiler I am using does not work well with them, anyway you could use them. Taking this into account and previosly defining a variable to handle the incoming data buffer like this:

#define isdigit(x)  isamong(x,"0123456789")
char    IPACK_Buff[IPACK_SIZE]; 

// Check if string is a valid IP
int IPACK_is_valid_ip(int len)
{
    int i = 0;
    int j = 0;
    int NumDots = 0;
    char number[4] = "000\0";

    // Check first  char is numeric
    if (!isdigit(IPACK_Buff[0])) 
        return 0;

    for (i = 0 ; i< len; i++)
    {
        if (isdigit(IPACK_Buff[i]))
        {
            number[j] = IPACK_Buff[i];
            j++;
            if (j>3)    
                return 0;
        }
        else if (IPACK_Buff[i] == '.')
        {
            if (atof(number)> 255) return 0;
            memset(number, '\0', 4);

            j = 0;
            NumDots++;
            if(NumDots>3)
                return 0;
        }
    }

    if (NumDots == 3)
    {
        return 1;
    }
    else 
        return 0;
}//

I hope this function helps you all. Again, take into account the low level this function is programmed before criticize.

Dilandau
  • 11
  • 2
1

I would use this regular expression (courtesy of Regular Expression Examples):

`\b(?:\d{1,3}\.){3}\d{1,3}\b`
Andrew Hare
  • 320,708
  • 66
  • 621
  • 623
  • Note: this will match IP4 addresses in dotted-decimal notation ONLY – Nick Whaley Apr 27 '09 at 01:37
  • This also doesn't detect if any octet is larger than 255. Regexes are a bit overkill for this problem. – Adam Rosenfield Apr 27 '09 at 02:01
  • if you fancy a bit of 'overkill' that's a little more effective, try this ^((([0-9]{1,2})|(1[0-9]{2,2})|(2[0-4][0-9])|(25[0-5])|\*)\.){3}(([0-9]{1,2})|(1[0-9]{2,2})|(2[0-4][0-9])|(25[0-5])|\*)$ (thanks to apoorv020 from my question http://stackoverflow.com/questions/2999282/regular-expression-to-match-ip-address-wildcard) – Ed James Jul 08 '10 at 10:59
1

I'll give the "don't want two problems" solution:

#include <string.h>



int isIp_v4( char* ip){
        int num;
        int flag = 1;
        int counter=0;
        char* p = strtok(ip,".");

        while (p && flag ){
                num = atoi(p);

                if (num>=0 && num<=255 && (counter++<4)){
                        flag=1;
                        p=strtok(NULL,".");

                }
                else{
                        flag=0;
                        break;
                }
        }

        return flag && (counter==3);

}

EDIT: strtok may not be thread safe (credits to Adam Rosenfield)

Tom
  • 39,851
  • 25
  • 129
  • 164
  • strtok is not necessarily thread-safe (it may be in some implementations, but it is not guaranteed to be). – Adam Rosenfield Apr 27 '09 at 02:02
  • @Adam: I see your point, but i think is reading too much between the lines. However, strtok could be replaced (when neccessary) with a custom thread safe strtok implementation. – Tom Apr 27 '09 at 02:09
  • `counter==3` should be `counter==4`. Apart from that, a nice simple solution. I would edit the code myself, but am <2k and really don't think I can find another 5 characters to change. – SiHa Jun 15 '16 at 15:38
0

I needed to figure out if incoming string "contains" a valid IP address, and to return a pointer to the portion of the incoming string that is the valid IP address, if so. If not, returns a null pointer.

Here is code that seems to work, although not well tested yet, I just wrote it and gave it a quick try. I didn't add a check yet for limiting the numbers to one-byte values, but do check to ensure that they are limited to three digit numbers.

int IsDigit(char ch)
{
   int is_digit = 0;
   if ( ch >= '0' && ch <= '9' )
   {
      is_digit = 1;
   }
   return is_digit;
}

#define FIND_IP_START         0
#define FIND_IP_DIGIT         1
#define FIND_IP_DIG_OR_DEC    2
#define FIND_IP_DECIMAL       3
#define FIND_IP_DIG_OR_END    4
#define FIND_IP_END           5
#define FIND_IP_DONE          6

char * StringContainsValidIpAddress(char * input_buf_pointer)
{
   char * pos       = input_buf_pointer;
   int    octets    = 0; 
   int    digits    = 0;
   int    state     = FIND_IP_START;
   char * ip_string = 0;

   char   ch        = *pos; 

   while ( (ch != NULL) && (state != FIND_IP_DONE) )
   {
      switch ( state )
      {
      case FIND_IP_START:
         if ( IsDigit(ch) )
         {
            ip_string = pos;  //potential start of ip string
            digits = 1;   // first digit
            octets = 1;   // of first octet
            state = FIND_IP_DIG_OR_DEC;
         }
         break;
      case FIND_IP_DIGIT:
         if ( IsDigit(ch) )
         {
            digits = 1;    // first digit
            octets++;      // of next octet
            if ( octets == 4 )
            {
               state = FIND_IP_DIG_OR_END;
            }
            else
            {
                   state = FIND_IP_DIG_OR_DEC;
            }
         }
         else
         {
            // Start over
            state = FIND_IP_START;
         }
         break;
      case FIND_IP_DIG_OR_DEC:
         // Here we are looking for another digit 
         // of the same octet or the decimal between 
         // octets.
         if (ch == '.')
         {
               state = FIND_IP_DIGIT;
         }
         else if ( IsDigit(ch) )
         {
            digits++;      // next digit
            if ( digits == 3 )
            {
               state = FIND_IP_DECIMAL;
            }
         }
         else
         {
            // Start over
            state = FIND_IP_START;
         }
         break;
      case FIND_IP_DECIMAL:
         if (ch == '.')
         {
               state = FIND_IP_DIGIT;
         }
         break;
      case FIND_IP_DIG_OR_END:
         // Here we are looking for another digit 
         // of the same octet or the end (which could
         // be a space or CR or LF or really any 
         // non-digit).
         if ( IsDigit(ch) )
         {
            digits++;      // next digit
            if ( digits == 3 )
            {
               state = FIND_IP_END;
            }
         }
         else
         {  
            *pos = 0;  // Null terminate the IP address string
            state = FIND_IP_DONE;
         }
         break;
      case FIND_IP_END:
         if ( !IsDigit(ch) )
         {
            *pos = 0;  // Null terminate the IP address string
            state = FIND_IP_DONE;
         }
         break;
      case FIND_IP_DONE:
         break;
      default:
         break;
      }

      // Fetch the next character
      ch = *++pos; 
   } 

   if (state == FIND_IP_DONE) 
   {
      return ip_string; 
   }
   else
   {
      return 0;
   }
}
0

Do it from scratch like this. This code contains tools to check if string contains IPv4 IP address.

#define MAX_HEX_NUMBER_COUNT 8 

int ishexdigit(char ch) 
{
   if((ch>='0'&&ch<='9')||(ch>='a'&&ch<='f')||(ch>='A'&&ch<='F'))
      return(1);
   return(0);
}

int IsIp6str(char *str)
{ 
   int hdcount=0;
   int hncount=0;
   int err=0;
   int packed=0;

   if(*str==':')
   {
      str++;    
      if(*str!=':')
         return(0);
      else
      {
         packed=1;
         hncount=1;
         str++;

         if(*str==0)
            return(1);
      }
   }

   if(ishexdigit(*str)==0)
   {
      return(0);        
   }

   hdcount=1;
   hncount=1;
   str++;

   while(err==0&&*str!=0)   
   {                      
      if(*str==':')
      {
         str++;
         if(*str==':')
         {
           if(packed==1)
              err=1;
           else
           {
              str++;

          if(ishexdigit(*str)||*str==0&&hncount<MAX_HEX_NUMBER_COUNT)
          {
             packed=1;
             hncount++;

             if(ishexdigit(*str))
             {
                if(hncount==MAX_HEX_NUMBER_COUNT)
                {
                   err=1;
                } else
                {
                   hdcount=1;
                   hncount++;
                   str++;   
                }
             }
          } else
          {
             err=1;
          }
       }
    } else
    {
           if(!ishexdigit(*str))
           {
              err=1;
           } else
           {
              if(hncount==MAX_HEX_NUMBER_COUNT)
              {
                 err=1;
              } else
              {
                  hdcount=1;
                  hncount++;
                  str++;   
              }
           }
        }
     } else
     {  
        if(ishexdigit(*str))
        {
           if(hdcount==4)
              err=1;
           else
           {
              hdcount++;          
              str++;
           }
         } else
            err=1;
     } 
   }

   if(hncount<MAX_HEX_NUMBER_COUNT&&packed==0)
      err=1;

    return(err==0);
}

int IsIp4str(char *str) 
{
   int nnumber=0;
   int value=0;
   int err=0;

   if(*str>='0'&&*str<='9')
   {
      value=*str-'0';
      str++;
   } else
      return(0);

   nnumber=1;

   while(err==0&&*str!=0)
   {
      if(*str>='0'&&*str<='9')
      {
         if(255/value>=10)
         {
            value*=10;

            if(255-value>=(*str-'0'))
            {
               value+=(*str-'0');
               str++;
            } else
                err=1;
         } else
           err=1;
      }  else
      {
         if(*str=='.')
         {      
            str++;
            if(*str>='0'&&*str<='9')
            {
               if(nnumber==4)
                  err=1;
               else
               {
                  if(*str=='0')
                  {
                     *str++;
                     if(*str!='.'&&*str!=0)
                        err=1;
                     else
                     {
                        nnumber++;
                        value=0;
                     }
                  } else
                  {
                     nnumber++;
                     value=*str-'0';
                     str++;
                  }
               }
            } else
            {
               err=1;
            }
         } else
           if(*str!=0)
             err=1;
      }
   }

   if(nnumber!=4)
      err=1;

   return(err==0);
}

Function IsIp4str(char *str) test if string contains IP address version four address format. IsIp6str(char *str) function test if string contains IP address version six address format.

Functions IsIp4str(char *str) and IsIp6str(char *str) returns true if string str contains IP address or false if string str not contains IP address.

If you need check if string contains IP address IPv6 format, it can done int IsIp6str(char *str) function. It works same way than

BenMorel
  • 30,280
  • 40
  • 163
  • 285
0

Heres the start of a function I've been working on, although not complete, it may spark ideas or comments. The thought behind the function is;

  1. Check the passed char pointer or string is an IPv4 address without port using its min/max size, how many dots in the string, and if the colon : character exists or not.
  2. If the string is not IPv4 with or without a port then check if the string is IPv6, if not IPv6 then IP format not recognized because it isn't implemented yet.

I think it depends on how deep you want to go into the issue, how deep you want to go to understand what problems could occur.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>

int isIP(char *ip)
{
    char *data_ptr = ip;    // Create a pointer to passed data
    int orig_str_size = 0;  // Create an int to hold passed data size
    int str_index = 0;      // Create an int to iterate individual ip characters
    int dot_count = 0;      // Create an int to check for the number of dots

    // Count the number of characters in data_ptr
    while (*data_ptr++ != '\0'){ orig_str_size++; }

    if(orig_str_size <= 0) // If nothing
    {
        printf("Get a grip, ip is empty\n\n");
        exit(0);
    }
    else // If within IPv4 size range
    if(orig_str_size >= 7 && orig_str_size <= INET_ADDRSTRLEN)
    {
        char *data1_ptr = ip; // Create a pointer to passed data
        printf("Within IPv4 range, %i characters in length\n\n", orig_str_size);

        // Count the number of dots in the string, 3 for IPv4
        for(str_index; str_index < orig_str_size; str_index++)
        {
            if(data1_ptr[str_index] == '.'){ dot_count++; }
        }

        // If theres 3 dots, while ignoring dots, check each char is a digit 
        if(dot_count == 3)
        {

            printf("There's three dots in the string\n\n");
            data1_ptr = ip;
            str_index = 0;

            // Iterate the string char by char
            for(str_index; str_index < orig_str_size; str_index++)
            {
                // Ignoring dots
                if(data1_ptr[str_index] != '.')
                { 
                    // If isdigit() is happy its a digit and isalpha() happy not alphabetic
                    if(isdigit(data1_ptr[str_index]) && !isalpha(data1_ptr[str_index]))
                    {
                        printf("Digit found and is not alphabetic\n\n");
                        continue;
                    }
                    else
                    if(!isdigit(data1_ptr[str_index]) && isalpha(data1_ptr[str_index]))
                    {
                        printf("Not a recognised IPv4 address, character detected in string\n\n");
                        exit(0);
                    }
                }
            }

            return 0;
        }
    }
    else // If IPv6
    if(orig_str_size > 0 && orig_str_size > INET_ADDRSTRLEN && orig_str_size <= INET6_ADDRSTRLEN)
    {
        printf("Within IPv6 range %i\n\n", orig_str_size);
        return 0;
    }
    else
    {
        printf("Unknown target format, the format you provided as a target is not implemented\n\n");
        exit(0);
    }

}

TCP/IP Internetworking

RFC791 - Internet Protocol - https://tools.ietf.org/html/rfc791

The CISCO Internetworking handbook http://docwiki.cisco.com/wiki/Internetworking_Technology_Handbook

The Open Systems Interconnection Reference Model http://docwiki.cisco.com/wiki/Internetworking_Basics#Open_Systems_Interconnection_Reference_Model

CISCO Troubleshooting TCP/IP Networks https://www.cisco.com/en/US/docs/internetworking/troubleshooting/guide/tr1907.pdf

What is the largest TCP/IP network port number allowable for IPv4?

0
//  you can even use the v value array to return the unsigned int 
//  version of the IP if desired in an unsigned int reference.   

bool isvalidip(const char * s) 
{
  char t[8];
  int p = 0;
  int v[8];
  int numnum = 0;
  for (int i = 0; i < (int) strlen(s); i++) {
    char c = s[i];
    int cgood = 0;
    if (c >= '0' && c <= '9' && p < 4) {
      t[p++] = c;
      t[p] = 0;
      cgood++;
      continue;
    }
    if (p == 4) return false;
    if (c == '.') {
      if (!p) return false;
      v[numnum++] = atoi(t);
      p = 0;
      cgood++;
      continue;
    }
    if (!cgood) return false; // not a valid character
    if (numnum > 4) return false; // we have a lot of dots....
  }
  v[numnum++] = atoi(t); // we did not have a dot, we had a NULL.....
  if (numnum != 4) return false; // we must have had 4 valid numbers....
  for (int i = 0; i < 4; i++)
  {
    if (v[i] < 0 || v[i] > 255) return false; // octet values out-of-range
  }
  return true; //we good..
}
0

I modify one of the answer to make it more complete and attach all the code (include test)

#include <stdio.h>
#include <assert.h>
#include <string.h>

int validateIP4Dotted(char *str, unsigned int pIPAddress[])
{
    int segs = 0; /* Segment count. */
    int chcnt = 0; /* Character count within segment. */
    int accum = 0; /* Accumulator for segment. */

    /* Catch NULL pointer. */

    if (str == NULL)
        return 0;

    /* Process every character in string. */

    while (*str != '\0')
    {
        /* Segment changeover. */

        if (*str == '.')
        {
            pIPAddress[segs] = accum;
            /* Must have some digits in segment. */

            if (chcnt == 0 || chcnt > 3)
                return 0;

            /* Limit number of segments. */

            if (++segs == 4)
                return 0;

            /* Reset segment values and restart loop. */

            chcnt = accum = 0;
            str++;
            continue;
        }
        /* Check numeric. */

        if ((*str < '0') || (*str > '9'))
            return 0;

        /* Accumulate and check segment. */

        if ((accum = accum * 10 + *str - '0') > 255)
            return 0;

        /* Advance other segment specific stuff and continue loop. */

        chcnt++;
        str++;
    }

    /* Check enough segments and enough characters in last segment. */
    pIPAddress[segs] = accum;

    if (segs != 3)
        return 0;

    if (chcnt == 0 || chcnt > 3)
        return 0;

    if (pIPAddress[0] >=224)
        return 0;
    /* Address okay. */

    return 1;
}


int main()
{
    unsigned int IpAddress[4];
    char str_ip[128];

    strcpy(str_ip, "192.168.1.10");
    assert(validateIP4Dotted(str_ip, IpAddress));
    assert(
            IpAddress[0] == 192 && IpAddress[1] == 168 && IpAddress[2] == 1
                    && IpAddress[3] == 10);

    strcpy(str_ip, "0.0.0.0");
    assert(validateIP4Dotted(str_ip, IpAddress));
    assert(
            IpAddress[0] == 0 && IpAddress[1] == 0 && IpAddress[2] == 0
                    && IpAddress[3] == 0);

    strcpy(str_ip, "/192.168.1.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "192..168.1.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, ".192.168.1.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "192.168.1.10.");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "192.168.1.10.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "192.168.1.");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "192.168.1");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "255.168.1.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "10.260.1.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    strcpy(str_ip, "10.200.0001.10");
    assert(!validateIP4Dotted(str_ip, IpAddress));

    return 0;
}
user7469511
  • 93
  • 1
  • 3
0

Try this code :

int ipValid(char *ip) {
int i,j,start,dotcount=0,x=0,end,c=0;
int n= strlen(ip);
start=0;
for(i=0;i<n;i++)
{
    if(ip[i]=='.'||i==n-1)
    {
        c=0;x=0;
        if(ip[i]=='.')
          {
            dotcount++;
            end=i-1;
           } 
        else if(i==n-1)
           end=i;
        for(j=start;j<=end;j++)
        {
            c++;
            x=x*10+(ip[j]-48);

        }
        if(c<4&&x>=0&&x<=255)
        {
            if(i==n-1)
                break;
            else
                start=i+1;
        }
        else
        {
            return 0;
        }
    }
}
if(dotcount==3)
   return 1;
else
   return 0;}
Suresh A
  • 11
  • 2
0

In the url/uri rfc 3986, the Augmented Backus-Naur Form (ABNF) ipv4 address is defined as:

  IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet

  dec-octet   = DIGIT                 ; 0-9
              / %x31-39 DIGIT         ; 10-99
              / "1" 2DIGIT            ; 100-199
              / "2" %x30-34 DIGIT     ; 200-249
              / "25" %x30-35          ; 250-255

I implemented the check with regexp in the following form:

// Although the RFC says ipv6 octects like 001 are not valid, it would be risky
// not to accept those
#define decoct "([01]?[0-9]?[0-9]|2[0-4][0-0]|25[0-5])"
#define ipv4 "(" decoct "\\." decoct "\\." decoct "\\." decoct ")"
piotr
  • 5,381
  • 1
  • 30
  • 56
-1

inet_addr() is much better than inet_aton() for number-and-dot notation representation IPv4 IP address checking.

Jalindar
  • 39
  • 1
-1

I think below C code snippet should work

bool validate_ip4(const char* buffer)
{
    if (NULL == buffer) return false;

    register const      char*   pos     = buffer;
    register unsigned   char    ch      = *pos;
    register unsigned   short   count   = 0;

    while (ch != NULL)
    {
        if (!((ch >= '0' && ch <= '9') || ch == '.')) return false;

        if (ch == '.')
            if (++count > 3) return false;

        ch = *++pos;
    }

    if (count == 3 && *--pos != '.') return true;

    return false;
}
LPL
  • 16,007
  • 6
  • 43
  • 87