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?
Asked
Active
Viewed 47 times
-3
-
1What have you tried so far? – Evg Nov 29 '20 at 15:57
-
1You can use the less-than operator for example. – eerorika Nov 29 '20 at 15:57
-
You could use a regex. – Eljay Nov 29 '20 at 16:02
-
I tried nothing because i dont know what would i do if someone typed 001 how do i convert that to integer of value 1. The whole address is 1 string btw. – Badplank Nov 29 '20 at 16:05
-
1Rather than parsing the numbers manually, why not use an existing function that is specifically designed to parse IP addresses? Like `inet_addr()`, `inet_pton()`, `getaddrinfo()`, etc. – Remy Lebeau Nov 29 '20 at 19:33
1 Answers
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