Open In App

Program to validate an IP address

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

Recommended Practice

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++




// Program to check if a given
// string is valid IPv4 address or not
#include <bits/stdc++.h>
using namespace std;
#define DELIM "."
 
/* function to check whether the
   string passed is valid or not */
bool valid_part(char* s)
{
    int n = strlen(s);
     
    // if length of passed string is
    // more than 3 then it is not valid
    if (n > 3)
        return false;
     
    // check if the string only contains digits
    // if not then return false
    for (int i = 0; i < n; i++)
        if ((s[i] >= '0' && s[i] <= '9') == false)
            return false;
    string str(s);
     
    // if the string is "00" or "001" or
    // "05" etc then it is not valid
    if (str.find('0') == 0 && n > 1)
        return false;
    stringstream geek(str);
    int x;
    geek >> x;
     
    // the string is valid if the number
    // generated is between 0 to 255
    return (x >= 0 && x <= 255);
}
 
/* return 1 if IP string is
valid, else return 0 */
int is_valid_ip(char* ip_str)
{
    // if empty string then return false
    if (ip_str == NULL)
        return 0;
    int i, num, dots = 0;
    int len = strlen(ip_str);
    int count = 0;
     
    // the number dots in the original
    // string should be 3
    // for it to be valid
    for (int i = 0; i < len; i++)
        if (ip_str[i] == '.')
            count++;
    if (count != 3)
        return false;
     
    // See following link for strtok()
   
    char *ptr = strtok(ip_str, DELIM);
    if (ptr == NULL)
        return 0;
 
    while (ptr) {
 
        /* after parsing string, it must be valid */
        if (valid_part(ptr))
        {
            /* parse remaining string */
            ptr = strtok(NULL, ".");
            if (ptr != NULL)
                ++dots;
        }
        else
            return 0;
    }
 
    /* valid IP string must contain 3 dots */
    // this is for the cases such as 1...1 where
    // originally the no. of dots is three but
    // after iteration of the string we find
    // it is not valid
    if (dots != 3)
        return 0;
    return 1;
}
 
// Driver code
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 "."
 
/* function to check whether the
   string passed is valid or not */
bool valid_part(const char* s)
{
    int n = strlen(s);
 
    // if length of passed string is
    // more than 3 then it is not valid
    if (n > 3)
        return false;
 
    // check if the string only contains digits
    // if not then return false
    for (int i = 0; i < n; i++)
        if (s[i] < '0' || s[i] > '9')
            return false;
 
    int x = atoi(s);
 
    // the string is valid if the number
    // generated is between 0 to 255
    return (x >= 0 && x <= 255);
}
 
/* return 1 if IP string is
   valid, else return 0 */
int is_valid_ip(char* ip_str)
{
    // if empty string then return false
    if (ip_str == NULL)
        return 0;
    int num, dots = 0;
    int len = strlen(ip_str);
    int count = 0;
 
    // the number dots in the original
    // string should be 3
    // for it to be valid
    for (int i = 0; i < len; i++)
        if (ip_str[i] == '.')
            count++;
    if (count != 3)
        return false;
 
    // See following link for strtok()
 
    char* ptr = strtok(ip_str, DELIM);
    if (ptr == NULL)
        return 0;
 
    while (ptr) {
 
        /* after parsing string, it must be valid */
        if (valid_part(ptr)) {
            /* parse remaining string */
            ptr = strtok(NULL, ".");
            if (ptr != NULL)
                ++dots;
        }
        else
            return 0;
    }
 
    /* valid IP string must contain 3 dots */
    // this is for the cases such as 1...1 where
    // originally the no. of dots is three but
    // after iteration of the string we find
    // it is not valid
    if (dots != 3)
        return 0;
    return 1;
}
 
// Driver code
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;
}


Java




import java.util.StringTokenizer;
 
public class Main {
    static final String DELIM = ".";
 
    // Function to check whether the string passed is valid or not
    static boolean isValidPart(String s) {
        int n = s.length();
 
        // If the length of the string is more than 3, then it is not valid
        if (n > 3)
            return false;
 
        // Check if the string only contains digits
        // If not, then return false
        for (int i = 0; i < n; i++)
            if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
                return false;
 
        // If the string is "00" or "001" or "05" etc then it is not valid
        if (s.indexOf('0') == 0 && n > 1)
            return false;
 
        try {
            int x = Integer.parseInt(s);
 
            // The string is valid if the number generated is between 0 to 255
            return (x >= 0 && x <= 255);
        } catch (NumberFormatException e) {
            return false;
        }
    }
 
    // Return 1 if IP string is valid, else return 0
    static int isValidIP(String ipStr) {
        // If the empty string then return false
        if (ipStr == null)
            return 0;
 
        int dots = 0;
        int len = ipStr.length();
        int count = 0;
 
        // The number dots in the original string should be 3
        // for it to be valid
        for (int i = 0; i < len; i++)
            if (ipStr.charAt(i) == '.')
                count++;
        if (count != 3)
            return 0;
 
        // Using StringTokenizer to split the IP string
        StringTokenizer st = new StringTokenizer(ipStr, DELIM);
 
        while (st.hasMoreTokens()) {
            String part = st.nextToken();
 
            // After parsing string, it must be valid
            if (isValidPart(part)) {
                // Parse remaining string
                if (st.hasMoreTokens())
                    dots++;
            } else
                return 0;
        }
 
        // Valid IP string must contain 3 dots
        // This is for cases such as 1...1 where
        // originally the number of dots is three but
        // after iteration of the string, we find it is not valid
        if (dots != 3)
            return 0;
 
        return 1;
    }
 
    // Driver code
    public static void main(String[] args) {
        String ip1 = "128.0.0.1";
        String ip2 = "125.16.100.1";
        String ip3 = "125.512.100.1";
        String ip4 = "125.512.100.abc";
 
        System.out.println(isValidIP(ip1) == 1 ? "Valid" : "Not valid");
        System.out.println(isValidIP(ip2) == 1 ? "Valid" : "Not valid");
        System.out.println(isValidIP(ip3) == 1 ? "Valid" : "Not valid");
        System.out.println(isValidIP(ip4) == 1 ? "Valid" : "Not valid");
    }
}


Python3




# Function to check whether the string passed is valid or not
def valid_part(s):
    n = len(s)
 
    # If the length of the passed string is more than 3, it is not valid
    if n > 3:
        return False
 
    # Check if the string only contains digits, if not, return false
    for i in range(n):
        if not s[i].isdigit():
            return False
 
    # Convert the string to an integer
    x = int(s)
 
    # The string is valid if the number generated is between 0 to 255
    return 0 <= x <= 255
 
# Return True if the IP string is valid, else return False
def is_valid_ip(ip_str):
    # If the string is empty, return False
    if ip_str is None:
        return False
 
    parts = ip_str.split('.')
    count = 0
 
    # The number of dots in the original string should be 3 for it to be valid
    for i in range(len(ip_str)):
        if ip_str[i] == '.':
            count += 1
 
    if count != 3:
        return False
 
    for part in parts:
        if not valid_part(part):
            return False
 
    return True
 
# Driver code
ip1 = "128.0.0.1"
ip2 = "125.16.100.1"
ip3 = "125.512.100.1"
ip4 = "125.512.100.abc"
 
# Check and print whether the IPs are valid or not
print("Valid" if is_valid_ip(ip1) else "Not valid")
print("Valid" if is_valid_ip(ip2) else "Not valid")
print("Valid" if is_valid_ip(ip3) else "Not valid")
print("Valid" if is_valid_ip(ip4) else "Not valid")


C#




// Program to check if a given
// string is valid IPv4 address or not
 
using System;
using System.Text.RegularExpressions;
 
class Program {
 
    /* function to check whether the
     string passed is valid or not */
    static bool ValidPart(string s)
    {
        int n = s.Length;
 
        // if length of passed string is
        // more than 3 then it is not valid
        if (n > 3)
            return false;
 
        // check if the string only contains digits
        // if not then return false
        for (int i = 0; i < n; i++) {
            if (!(s[i] >= '0' && s[i] <= '9'))
                return false;
        }
 
        string str = s;
 
        // if the string is "00" or "001" or
        // "05" etc then it is not valid
        if (str.IndexOf('0') == 0 && n > 1)
            return false;
 
        // the string is valid if the number
        // generated is between 0 to 255
        if (int.TryParse(str, out int x)) {
            return (x >= 0 && x <= 255);
        }
 
        return false;
    }
 
    /* return 1 if IP string is
  valid, else return 0 */
    static int IsValidIP(string ipStr)
    {
 
        // if empty string then return false
        if (ipStr == null)
            return 0;
 
        int count = 0;
        int len = ipStr.Length;
 
        // the number dots in the original
        // string should be 3
        // for it to be valid
        for (int i = 0; i < len; i++) {
            if (ipStr[i] == '.') {
                count++;
            }
        }
 
        if (count != 3) {
            return 0;
        }
 
        string[] parts = ipStr.Split('.');
 
        if (parts.Length != 4) {
            return 0;
        }
 
        foreach(string part in parts)
        {
            if (!ValidPart(part)) {
                return 0;
            }
        }
 
        return 1;
    }
 
    static void Main(string[] args)
    {
        string ip1 = "128.0.0.1";
        string ip2 = "125.16.100.1";
        string ip3 = "125.512.100.1";
        string ip4 = "125.512.100.abc";
 
        Console.WriteLine(
            IsValidIP(ip1) == 1 ? "Valid" : "Not valid");
        Console.WriteLine(
            IsValidIP(ip2) == 1 ? "Valid" : "Not valid");
        Console.WriteLine(
            IsValidIP(ip3) == 1 ? "Valid" : "Not valid");
        Console.WriteLine(
            IsValidIP(ip4) == 1 ? "Valid" : "Not valid");
    }
}


Javascript




// Function to check whether the string passed is valid or not
function validPart(s) {
    const n = s.length;
     
    // If the length of the passed string is more than 3, it is not valid
    if (n > 3) {
        return false;
    }
     
    // Check if the string only contains digits, if not, return false
    for (let i = 0; i < n; i++) {
        if (!(s[i] >= '0' && s[i] <= '9')) {
            return false;
        }
    }
     
    // Convert the string to an integer
    const x = parseInt(s);
     
    // The string is valid if the number generated is between 0 to 255
    return (x >= 0 && x <= 255);
}
 
// Return true if the IP string is valid, else return false
function isValidIP(ipStr) {
    // If the string is empty, return false
    if (ipStr === null) {
        return false;
    }
     
    const parts = ipStr.split('.');
    let count = 0;
     
    // The number of dots in the original string should be 3 for it to be valid
    for (let i = 0; i < ipStr.length; i++) {
        if (ipStr[i] === '.') {
            count++;
        }
    }
     
    if (count !== 3) {
        return false;
    }
 
    for (let i = 0; i < parts.length; i++) {
        if (!validPart(parts[i])) {
            return false;
        }
    }
     
    return true;
}
 
// Driver code
const ip1 = "128.0.0.1";
const ip2 = "125.16.100.1";
const ip3 = "125.512.100.1";
const ip4 = "125.512.100.abc";
 
isValidIP(ip1) ? console.log("Valid") : console.log("Not valid");
isValidIP(ip2) ? console.log("Valid") : console.log("Not valid");
isValidIP(ip3) ? console.log("Valid") : console.log("Not valid");
isValidIP(ip4) ? console.log("Valid") : console.log("Not valid");


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 .

C++




#include <iostream>
#include <sstream>
 
// Function to check if a number is in the range 0-255
bool inRange(int n) {
    return (n >= 0 && n <= 255);
}
 
// Function to check if a string has a leading zero
bool hasLeadingZero(const std::string& n) {
    if (n.length() > 1) {
        if (n[0] == '0') {
            return true;
        }
    }
    return false;
}
 
// Function to validate an IP address string
int isValid(const std::string& s) {
    // Using stringstream to split the string by '.'
    std::istringstream ss(s);
    std::string part;
    int count = 0;
     
    // Loop through each part of the IP address
    while (getline(ss, part, '.')) {
        count++;
 
        // Check for leading zeros in each part
        if (hasLeadingZero(part)) {
            return 0; // Invalid if leading zero is present
        }
 
        // Check if part is empty
        if (part.length() == 0) {
            return 0; // Invalid if part is empty
        }
 
        // Try converting the part to an integer
        try {
            int num = std::stoi(part);
 
            // Check if the integer is in the valid range
            if (!inRange(num)) {
                return 0; // Invalid if not in the range 0-255
            }
        }
        catch (std::invalid_argument const& e) {
            return 0; // Invalid if conversion to integer fails
        }
    }
 
    // Check if there are exactly 4 parts in the IP address
    return (count == 4) ? 1 : 0;
}
 
int main() {
    // Test IP addresses
    std::string ip1 = "222.111.111.111";
    std::string ip2 = "5555..555";
    std::string ip3 = "0000.0000.0000.0000";
    std::string ip4 = "1.1.1.1";
     
    // Print the validation result for each IP address
    std::cout << isValid(ip1) << std::endl;
    std::cout << isValid(ip2) << std::endl;
    std::cout << isValid(ip3) << std::endl;
    std::cout << isValid(ip4) << std::endl;
 
    return 0;
}


Java




public class GFG {
 
    public static boolean inRange(int n)
    { // check if every split is in range 0-255
        if (n >= 0 && n <= 255) {
            return true;
        }
        return false;
    }
 
    public static boolean hasLeadingZero(String n)
    { // check if every split has leading zero or not.
        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) { // if number of splitting element is not
                    // 4 it is not a valid IP address
            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));
    }
}


Python3




def in_range(n):   #check if every split is in range 0-255
    if n >= 0 and n<=255:
        return True
    return False
     
def has_leading_zero(n): # check if every split has leading zero or not.
    if len(n)>1:
        if n[0] == "0":
            return True
    return False
def isValid(s):
     
    s = s.split(".")
    if len(s) != 4#if number of splitting element is not 4 it is not a valid ip address
        return 0
    for n in s:
         
        if has_leading_zero(n):
            return 0
        if len(n) == 0:
            return 0
        try#if int(n) is not an integer it raises an error
            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))
 
     
 # this code is contributed by Vivek Maddeshiya.


C#




using System;
 
class GFG
{
    // Function to check if a number is in the range 0-255
    static bool InRange(int n)
    {
        return (n >= 0 && n <= 255);
    }
 
    // Function to check if a string has a leading zero
    static bool HasLeadingZero(string n)
    {
        if (n.Length > 1 && n[0] == '0')
        {
            return true;
        }
        return false;
    }
 
    // Function to validate an IP address string
    static int IsValid(string s)
    {
        // Split the string by '.'
        string[] parts = s.Split('.');
        int count = 0;
 
        // Loop through each part of the IP address
        foreach (string part in parts)
        {
            count++;
 
            // Check for leading zeros in each part
            if (HasLeadingZero(part))
            {
                return 0; // Invalid if leading zero is present
            }
 
            // Check if part is empty
            if (part.Length == 0)
            {
                return 0; // Invalid if part is empty
            }
 
            // Try converting the part to an integer
            if (!int.TryParse(part, out int num))
            {
                return 0; // Invalid if conversion to integer fails
            }
 
            // Check if the integer is in the valid range
            if (!InRange(num))
            {
                return 0; // Invalid if not in the range 0-255
            }
        }
 
        // Check if there are exactly 4 parts in the IP address
        return (count == 4) ? 1 : 0;
    }
 
    static void Main()
    {
        // Test IP addresses
        string ip1 = "222.111.111.111";
        string ip2 = "5555..555";
        string ip3 = "0000.0000.0000.0000";
        string ip4 = "1.1.1.1";
 
        // Print the validation result for each IP address
        Console.WriteLine(IsValid(ip1));
        Console.WriteLine(IsValid(ip2));
        Console.WriteLine(IsValid(ip3));
        Console.WriteLine(IsValid(ip4));
    }
}


Javascript




function inRange(n) {
  // check if every split is in range 0-255
  if (n >= 0 && n <= 255) {
    return true;
  }
  return false;
}
 
function hasLeadingZero(n) {
  // check if every split has leading zero or not.
  if (n.length > 1) {
    if (n.charAt(0) === '0') {
      return true;
    }
  }
  return false;
}
 
function isValid(s) {
  let parts = s.split('.');
  if (parts.length !== 4) { // if number of splitting element is not 4 it is not a valid IP address
    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));


Output

1
0
0
1


Time complexity : O(n) 
Auxiliary Space : O(1)

Method 3 –  Using String stream and vector 

Approach 

  1. 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”]
  2.  If the vector size != 4 return false,  like 222.111.111.111  v = [“222” , “111”  , “111”  , “111”]. 
  3.  Iterating over the generated vector of string  
  4.  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;
  5.  For test case like a.b.c.d , checking the alpha values like abcde…… if any present simply return false
  6.  And lastly we are checking if the number is greater than 255 or not  
     

C++




// Program to check if a given
// string is valid IPv4 address or not
#include <bits/stdc++.h>
using namespace std;
 
/* return 1 if IP string is
valid, else return 0 */
int is_valid_ip(string s)
{
    // code here
    int n = s.size();
    // for test case like 1...1 or something lesser than 7
    if (n < 7)
        return false;
    // 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"]
    vector<string> v;
    stringstream ss(s);
    while (ss.good()) {
        string substr;
        getline(ss, substr, '.');
        v.push_back(substr);
    }
    // If the vector size != 4 return false,  like
    // 222.111.111.111  v = ["222" , "111"  , "111"  ,
    // "111"].
    if (v.size() != 4)
        return false;
    // Iterating over the generated vector of string
    for (int i = 0; i < v.size(); i++) {
        //
        string temp = v[i];
        // for leading zero , test case like 222.0.0.10 this
        // is valid but this is not vaild 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;
        if (temp.size() > 1) {
            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
 
        for (int j = 0; j < temp.size(); j++) {
            if (isalpha(temp[j]))
                return false;
        }
        // And lastly we are checking if the number is
        // greater than 255 or not
 
        if (stoi(temp) > 255)
            return false;
    }
    return true;
}
 
// Driver code
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;
}


Java




import java.util.StringTokenizer;
 
class Main {
    // Function to check if a given
    // string is a valid IPv4 address or not
    static boolean isValidIP(String s) {
        int n = s.length();
         
        // for test cases like 1...1 or something lesser than 7
        if (n < 7)
            return false;
 
        // Using StringTokenizer to separate all the strings from
        // '.' and push back into vector like for example -
        // 222.111.111.111 vector is v = ["222", "111", "111", "111"]
        StringTokenizer st = new StringTokenizer(s, ".");
        int count = 0;
        while (st.hasMoreTokens()) {
            String substr = st.nextToken();
            count++;
 
            // If the substring size is greater than 1 and the first character is '0', return false
            if (substr.length() > 1 && substr.charAt(0) == '0')
                return false;
 
            // For substrings like a.b.c.d, checking if any character is non-numeric
            for (int j = 0; j < substr.length(); j++) {
                if (!Character.isDigit(substr.charAt(j)))
                    return false;
            }
 
            // Check if the number is greater than 255
            if (Integer.parseInt(substr) > 255)
                return false;
        }
 
        // If the count of substrings is not 4, return false
        if (count != 4)
            return false;
 
        return true;
    }
 
    // Driver code
    public static void main(String[] args) {
        String s1 = "128.0.0.1";
        String s2 = "125.16.100.1";
        String s3 = "125.512.100.1";
        String s4 = "125.512.100.abc";
 
        System.out.println(isValidIP(s1) ? "Valid" : "Not valid");
        System.out.println(isValidIP(s2) ? "Valid" : "Not valid");
        System.out.println(isValidIP(s3) ? "Valid" : "Not valid");
        System.out.println(isValidIP(s4) ? "Valid" : "Not valid");
    }
}


Python




def is_valid_ip(s):
    n = len(s)
 
    # for test cases like 1...1 or something lesser than 7
    if n < 7:
        return False
 
    # Using split to separate all the strings from '.'
    # and create a list like for example -
    # "222.111.111.111" becomes ["222", "111", "111", "111"]
    substrings = s.split(".")
    count = 0
 
    for substr in substrings:
        count += 1
 
        # If the substring size is greater than 1 and the first character is '0', return false
        if len(substr) > 1 and substr[0] == '0':
            return False
 
        # For substrings like a.b.c.d, checking if any character is non-numeric
        if not substr.isdigit():
            return False
 
        # Check if the number is greater than 255
        if int(substr) > 255:
            return False
 
    # If the count of substrings is not 4, return false
    if count != 4:
        return False
 
    return True
 
 
# Driver code
s1 = "128.0.0.1"
s2 = "125.16.100.1"
s3 = "125.512.100.1"
s4 = "125.512.100.abc"
 
print("Valid" if is_valid_ip(s1) else "Not valid")
print("Valid" if is_valid_ip(s2) else "Not valid")
print("Valid" if is_valid_ip(s3) else "Not valid")
print("Valid" if is_valid_ip(s4) else "Not valid")


C#




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
 
class Program
{
    /* Return true if IP string is valid, else return false */
    static bool IsValidIP(string s)
    {
        int n = s.Length;
         
        // For test cases like 1...1 or something lesser than 7
        if (n < 7)
            return false;
 
        // Using regex to match and separate all the strings from '.'
        var matches = Regex.Matches(s, @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
 
        // If the number of matches is not 1, return false
        if (matches.Count != 1)
            return false;
 
        // Extract the matched IP string
        var ipString = matches[0].Value;
 
        // Split the IP string by '.' and store in an array
        string[] parts = ipString.Split('.');
 
        // If the array length != 4, return false
        if (parts.Length != 4)
            return false;
 
        // Iterating over the array of strings
        for (int i = 0; i < parts.Length; i++)
        {
            string temp = parts[i];
 
            // For leading zero, check if the string is "0" or starts with '0'
            if (temp.Length > 1 && temp[0] == '0')
                return false;
 
            // For alphanumeric characters, return false
            if (temp.Any(char.IsLetter))
                return false;
 
            // Check if the number is greater than 255
            if (int.Parse(temp) > 255)
                return false;
        }
        return true;
    }
 
    // Driver code
    static void 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";
 
        Console.WriteLine(IsValidIP(s1) ? "Valid" : "Not valid");
        Console.WriteLine(IsValidIP(s2) ? "Valid" : "Not valid");
        Console.WriteLine(IsValidIP(s3) ? "Valid" : "Not valid");
        Console.WriteLine(IsValidIP(s4) ? "Valid" : "Not valid");
    }
}


Javascript




function isValidIP(s) {
    const n = s.length;
    if (n < 7) return false;
 
    const v = s.split('.');
    if (v.length !== 4) return false;
 
    for (let i = 0; i < v.length; i++) {
        const temp = v[i];
        if (temp.length > 1 && temp[0] === '0') return false;
 
        for (let j = 0; j < temp.length; j++) {
            if (isNaN(temp[j])) return false;
        }
 
        if (parseInt(temp) > 255) return false;
    }
    return true;
}
 
// Driver code
const s1 = "128.0.0.1";
const s2 = "125.16.100.1";
const s3 = "125.512.100.1";
const s4 = "125.512.100.abc";
 
isValidIP(s1) ? console.log("Valid") : console.log("Not valid");
isValidIP(s2) ? console.log("Valid") : console.log("Not valid");
isValidIP(s3) ? console.log("Valid") : console.log("Not valid");
isValidIP(s4) ? console.log("Valid") : console.log("Not valid");
//This article is contributed by Utkarsh


Output

Valid
Valid
Not valid
Not valid


Time complexity : O(n) 
Auxiliary Space : O(1)



Last Updated : 13 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads