Write a program to Validate an IPv4 Address.
According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1
Following are steps to check whether a given string is a valid IPv4 address or not:
step 1) Parse string with “.” as delimiter using “strtok()” function.
e.g.ptr = strtok(str, DELIM);
step 2)
A) If ptr contains any character which is not digit then return 0
B) Convert “ptr” to decimal number say ‘NUM’
C) If NUM is not in range of 0-255 return 0
D) If NUM is in range of 0-255 and ptr is non-NULL increment “dot_counter” by 1
E) if ptr is NULL goto step 3 else goto step 1
step 3) if dot_counter != 3 return 0 else return 1
C++
#include <bits/stdc++.h>
using namespace std;
#define DELIM "."
bool valid_part( char * s)
{
int n = strlen (s);
if (n > 3)
return false ;
for ( int i = 0; i < n; i++)
if ((s[i] >= '0' && s[i] <= '9' ) == false )
return false ;
string str(s);
if (str.find( '0' ) == 0 && n > 1)
return false ;
stringstream geek(str);
int x;
geek >> x;
return (x >= 0 && x <= 255);
}
int is_valid_ip( char * ip_str)
{
if (ip_str == NULL)
return 0;
int i, num, dots = 0;
int len = strlen (ip_str);
int count = 0;
for ( int i = 0; i < len; i++)
if (ip_str[i] == '.' )
count++;
if (count != 3)
return false ;
char *ptr = strtok (ip_str, DELIM);
if (ptr == NULL)
return 0;
while (ptr) {
if (valid_part(ptr))
{
ptr = strtok (NULL, "." );
if (ptr != NULL)
++dots;
}
else
return 0;
}
if (dots != 3)
return 0;
return 1;
}
int main()
{
char ip1[] = "128.0.0.1" ;
char ip2[] = "125.16.100.1" ;
char ip3[] = "125.512.100.1" ;
char ip4[] = "125.512.100.abc" ;
is_valid_ip(ip1) ? cout<< "Valid\n" : cout<< "Not valid\n" ;
is_valid_ip(ip2) ? cout<< "Valid\n" : cout<< "Not valid\n" ;
is_valid_ip(ip3) ? cout<< "Valid\n" : cout<< "Not valid\n" ;
is_valid_ip(ip4) ? cout<< "Valid\n" : cout<< "Not valid\n" ;
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define DELIM "."
bool valid_part( const char * s)
{
int n = strlen (s);
if (n > 3)
return false ;
for ( int i = 0; i < n; i++)
if (s[i] < '0' || s[i] > '9' )
return false ;
int x = atoi (s);
return (x >= 0 && x <= 255);
}
int is_valid_ip( char * ip_str)
{
if (ip_str == NULL)
return 0;
int num, dots = 0;
int len = strlen (ip_str);
int count = 0;
for ( int i = 0; i < len; i++)
if (ip_str[i] == '.' )
count++;
if (count != 3)
return false ;
char * ptr = strtok (ip_str, DELIM);
if (ptr == NULL)
return 0;
while (ptr) {
if (valid_part(ptr)) {
ptr = strtok (NULL, "." );
if (ptr != NULL)
++dots;
}
else
return 0;
}
if (dots != 3)
return 0;
return 1;
}
int main()
{
char ip1[] = "128.0.0.1" ;
char ip2[] = "125.16.100.1" ;
char ip3[] = "125.512.100.1" ;
char ip4[] = "125.512.100.abc" ;
is_valid_ip(ip1) ? printf ( "Valid\n" )
: printf ( "Not valid\n" );
is_valid_ip(ip2) ? printf ( "Valid\n" )
: printf ( "Not valid\n" );
is_valid_ip(ip3) ? printf ( "Valid\n" )
: printf ( "Not valid\n" );
is_valid_ip(ip4) ? printf ( "Valid\n" )
: printf ( "Not valid\n" );
return 0;
}
|
Output
Valid
Valid
Not valid
Not valid
Time complexity : O(n)
Auxiliary Space : O(1)
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python Solution :-
Approach:- We will check all the cases where ip address may be invalid
1. First we will split the given input using split() function then check if it has a length of 4 or not .If length is not equal to 4 then we will directly return 0.
2. in second step we will check if any split element contains any leading zero or not .if it is then we will return zero.
3.If any of the split does not contain any number then it is not a valid ip address .so we will return 0
4. Then we will check if all the splits are in the range of 0-255 or not .If not we will return 0.
5.Finally if none of the above condition is true we can finally say that it is a valid ip address.And we will return True.
Here is the code for above approach .
Python3
def in_range(n):
if n > = 0 and n< = 255 :
return True
return False
def has_leading_zero(n):
if len (n)> 1 :
if n[ 0 ] = = "0" :
return True
return False
def isValid(s):
s = s.split( "." )
if len (s) ! = 4 :
return 0
for n in s:
if has_leading_zero(n):
return 0
if len (n) = = 0 :
return 0
try :
n = int (n)
if not in_range(n):
return 0
except :
return 0
return 1
if __name__ = = "__main__" :
ip1 = "222.111.111.111"
ip2 = "5555..555"
ip3 = "0000.0000.0000.0000"
ip4 = "1.1.1.1"
print (isValid(ip1))
print (isValid(ip2))
print (isValid(ip3))
print (isValid(ip4))
|
Java
public class GFG {
public static boolean inRange( int n)
{
if (n >= 0 && n <= 255 ) {
return true ;
}
return false ;
}
public static boolean hasLeadingZero(String n)
{
if (n.length() > 1 ) {
if (n.charAt( 0 ) == '0' ) {
return true ;
}
}
return false ;
}
public static int isValid(String s)
{
String[] parts = s.split( "\\." );
if (parts.length
!= 4 ) {
return 0 ;
}
for (String part : parts) {
if (hasLeadingZero(part)) {
return 0 ;
}
if (part.length() == 0 ) {
return 0 ;
}
try {
int num = Integer.parseInt(part);
if (!inRange(num)) {
return 0 ;
}
}
catch (NumberFormatException e) {
return 0 ;
}
}
return 1 ;
}
public static void main(String[] args)
{
String ip1 = "222.111.111.111" ;
String ip2 = "5555..555" ;
String ip3 = "0000.0000.0000.0000" ;
String ip4 = "1.1.1.1" ;
System.out.println(isValid(ip1));
System.out.println(isValid(ip2));
System.out.println(isValid(ip3));
System.out.println(isValid(ip4));
}
}
|
Javascript
function inRange(n) {
if (n >= 0 && n <= 255) {
return true ;
}
return false ;
}
function hasLeadingZero(n) {
if (n.length > 1) {
if (n.charAt(0) === '0' ) {
return true ;
}
}
return false ;
}
function isValid(s) {
let parts = s.split( '.' );
if (parts.length !== 4) {
return 0;
}
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (hasLeadingZero(part)) {
return 0;
}
if (part.length === 0) {
return 0;
}
try {
let num = parseInt(part, 10);
if (!inRange(num)) {
return 0;
}
} catch (e) {
return 0;
}
}
return 1;
}
let ip1 = "222.111.111.111" ;
let ip2 = "5555..555" ;
let ip3 = "0000.0000.0000.0000" ;
let ip4 = "1.1.1.1" ;
console.log(isValid(ip1));
console.log(isValid(ip2));
console.log(isValid(ip3));
console.log(isValid(ip4));
|
Time complexity : O(n)
Auxiliary Space : O(1)
Method 3 – Using String stream and vector
Approach
- Using string stream to separate all the string from ‘.’ and push back into vector like for ex – 222.111.111.111 vector is v = [“222” , “111” , “111” , “111”]
- If the vector size != 4 return false, like 222.111.111.111 v = [“222” , “111” , “111” , “111”].
- Iterating over the generated vector of string
- for leading zero , test case like 222.0.0.10 this is valid but this is not 222.00.100.100 , we check for the size of the i th string if temp.size() > 1 and if(temp[0] == ‘0’) return false;
- For test case like a.b.c.d , checking the alpha values like abcde…… if any present simply return false
- And lastly we are checking if the number is greater than 255 or not
C++
#include <bits/stdc++.h>
using namespace std;
int is_valid_ip(string s)
{
int n = s.size();
if (n < 7)
return false ;
vector<string> v;
stringstream ss(s);
while (ss.good()) {
string substr;
getline(ss, substr, '.' );
v.push_back(substr);
}
if (v.size() != 4)
return false ;
for ( int i = 0; i < v.size(); i++) {
string temp = v[i];
if (temp.size() > 1) {
if (temp[0] == '0' )
return false ;
}
for ( int j = 0; j < temp.size(); j++) {
if ( isalpha (temp[j]))
return false ;
}
if (stoi(temp) > 255)
return false ;
}
return true ;
}
int main()
{
string s1 = "128.0.0.1" ;
string s2 = "125.16.100.1" ;
string s3 = "125.512.100.1" ;
string s4 = "125.512.100.abc" ;
is_valid_ip(s1) ? cout << "Valid\n"
: cout << "Not valid\n" ;
is_valid_ip(s2) ? cout << "Valid\n"
: cout << "Not valid\n" ;
is_valid_ip(s3) ? cout << "Valid\n"
: cout << "Not valid\n" ;
is_valid_ip(s4) ? cout << "Valid\n"
: cout << "Not valid\n" ;
return 0;
}
|
Output
Valid
Valid
Not valid
Not valid
Time complexity : O(n)
Auxiliary Space : O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!