-3

it's for detecting ipv4 adressess for instance: 255.255.1.0 = true 277.255.1.0 = false because 277 is higher than 255 how do i detect this on every number seperated by comas? Anyone got an idea?

1 Answers1

1

You can split your string into four numbers via the sscanf function from the <cstdio> header as follows:

    std::string test = "1.1.1.1";
    int numbers[4];
    //Check if returned value is 4 if you aren't sure the input is in the right format
    sscanf( test.c_str(), "%i.%i.%i.%i", &numbers[0], &numbers[1], &numbers[2], &numbers[3] );

After that you can iterate the array to check for invalid numbers or use <algorithm>:

    bool valid = std::none_of( a, a + 4, []( int i ){ return ( i < 0 ) || ( i > 255 ); });

However if you are writing something networking-related I would just check the return-value of inet_pton, since you will probably make that function call anyway and it return 1 on success and 0 if the supplied string is not a valid address.

Orcthanc
  • 49
  • 1
  • 6