Validate Ip Address

Solution For Validate Ip Address

Problem Statement:

Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.

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.

Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.

IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (“:”). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address (Omit leading zeros, and using upper cases).

However, we don’t replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.

Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.

Note: You may assume there is no extra space or special characters in the input string.

Examples:

Input: “172.16.254.1”
Output: “IPv4”
Explanation: This is a valid IPv4 address, return “IPv4”.

Input: “2001:0db8:85a3:0:0:8A2E:0370:7334”
Output: “IPv6”
Explanation: This is a valid IPv6 address, return “IPv6”.

Input: “256.256.256.256”
Output: “Neither”
Explanation: This is neither a IPv4 address nor a IPv6 address.

Approach:

The problem statement clearly states the format of valid IPv4 and IPv6 addresses. The solution involves splitting the input string based on the separator (dot “.” for IPv4 and colon “:” for IPv6) and validating each group at each index.

For IPv4:
Each group should be in the range of 0 to 255 (inclusive) and should not contain any leading zeros.

For IPv6:
Each group should be a hexadecimal number of exactly 4 digits. The input string can have lower-case alphabets, which can be converted to upper-case alphabets. Also, consecutive groups of zero can only be replaced by “::” if there are no other zero groups in-between them. So the total number of groups in the final string cannot exceed 8.

Solution:

  • First, we split the input string based on the separator (dot “.” or colon “:”).
  • If the string has neither 3 dots nor 7 colons, return “Neither”
  • If the string has 3 dots but not 4 groups after splitting, return “Neither”
  • If the string has 7 colons but not 8 groups after splitting, return “Neither”
  • If the string has both dots and colons, return “Neither” (it can’t be both IPv4 and IPv6)
  • For IPv4, check if each group is a decimal number between 0 and 255 (inclusive) and doesn’t have leading zeros.
  • For IPv6, check if each group is a hexadecimal number of exactly 4 digits and the total number of groups in the final string doesn’t exceed 8.

Code:

Here is the commented Python code for the above approach:

def validateIPAddress(IP: str) -> str:

# Check if IPv4 - if yes, validate and return "IPv4"
if '.' in IP:
    groups = IP.split('.')
    if len(groups) != 4:    # should have 4 groups
        return "Neither"
    for group in groups:
        if not group.isdigit() or not 0 <= int(group) <= 255 or (group[0] == '0' and len(group) > 1):
            # should contain only digits, be between 0 and 255, and not have leading zeros
            return "Neither"
    return "IPv4"

# Check if IPv6 - if yes, validate and return "IPv6"
elif ':' in IP:
    groups = IP.split(':')
    if len(groups) != 8:    # should have 8 groups
        return "Neither"
    for group in groups:
        # should contain only hexadecimal digits (0-9, a-f or A-F) and have exactly 4 digits
        if not all(char in '0123456789abcdefABCDEF' for char in group) or len(group) > 4 or group.count('0') > 3:
            return "Neither"
    # Replace consecutive zero groups with "::" and count total number of groups
    IP = IP.replace('::', ':'+':'*8, 1)
    if IP.count(':') != 7:    # should have exactly 8 groups after replacement
        return "Neither"
    return "IPv6"

# Neither IPv4 nor IPv6
return "Neither"

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(1). We only store the groups after splitting the input string.

Step by Step Implementation For Validate Ip Address

/**
 * Valid IP Address
 * 
 * Given a string IP. We need to check If IP is a valid IPv4 address, valid IPv6 address or not a valid IP address.
 * 
 * IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255 inclusive, separated by dots ("."), e.g.,172.16.254.1;
 * 
 * Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.
 * 
 * IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).
 * 
 * However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.
 * 
 * Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.
 * 
 * Note: You may assume there is no extra space or special characters in the input string.
 * 
 * Example 1:
 * Input: "172.16.254.1"
 * 
 * Output: "IPv4"
 * 
 * Explanation: This is a valid IPv4 address, return "IPv4".
 * 
 * Example 2:
 * Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
 * 
 * Output: "IPv6"
 * 
 * Explanation: This is a valid IPv6 address, return "IPv6".
 * 
 * Example 3:
 * Input: "256.256.256.256"
 * 
 * Output: "Neither"
 * 
 * Explanation: This is neither a IPv4 address nor a IPv6 address.
 */

class Solution {
    public String validIPAddress(String IP) {
        if (isValidIPv4(IP)) return "IPv4";
        else if (isValidIPv6(IP)) return "IPv6";
        else return "Neither";
    }
    
    public boolean isValidIPv4(String ip) {
        if (ip.length() < 7) return false;
        if (ip.charAt(0) == '.') return false;
        if (ip.charAt(ip.length() - 1) == '.') return false;
        String[] tokens = ip.split("\\.");
        if (tokens.length != 4) return false;
        for (String token : tokens) {
            if (!isValidIPv4Token(token)) return false;
        }
        return true;
    }
    
    public boolean isValidIPv4Token(String token) {
        if (token.startsWith("0") && token.length() > 1) return false;
        try {
            int parsedInt = Integer.parseInt(token);
            if (parsedInt < 0 || parsedInt > 255) return false;
            if (parsedInt == 0 && token.charAt(0) != '0') return false;
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
    
    public boolean isValidIPv6(String ip) {
        if (ip.length() < 15) return false;
        if (ip.charAt(0) == ':') return false;
        if (ip.charAt(ip.length() - 1) == ':') return false;
        String[] tokens = ip.split(":");
        if (tokens.length != 8) return false;
        for (String token : tokens) {
            if (!isValidIPv6Token(token)) return false;
        }
        return true;
    }
    
    public boolean isValidIPv6Token(String token) {
        if (token.length() > 4 || token.length() == 0) return false;
        char[] chars = token.toCharArray();
        for (char c : chars) {
            boolean isDigit = c >= 48 && c <= 57;
            boolean isUppercaseAF = c >= 65 && c <= 70;
            boolean isLowerCaseAF = c >= 97 && c <= 102;
            if (!(isDigit || isUppercaseAF || isLowerCaseAF)) 
                return false;
        }
        return true;
    }
}
def validateIP(self, IP): 

# The given string is empty then it is not a valid ip address 
if len(IP) == 0: 
return "Neither"

# Counting the no. of dots in the string 
res = IP.count('.') 

# Checking the ip address for IPv4 
if res == 3: 

# Splitting the string into list of parts 
s = IP.split('.') 

# Checking for the valid ip 
for i in s: 

# If any part of the ip 
# is not equal to digit 
# or is greater than 255 
# then it is not a valid 
# ip address for IPv4 
if not i.isdigit() or int(i) > 255: 
return "Neither"

# If we reach here means 
# it is a valid IPv4 address 
return "IPv4"

# Checking the ip address for IPv6 
if res == 7: 

# Splitting the string into list of parts 
s = IP.split(':') 

# Checking for the valid ip 
for i in s: 

# If length of any part is 
# greater than 4 or less than 1 
# or contains any non-hexadecimal 
# character then it is not 
# a valid ip address for IPv6 
if len(i) > 4 or len(i) < 1 or not i.isalnum(): 
return "Neither"

# If we reach here means 
# it is a valid IPv6 address 
return "IPv6"

# If we reach here it means 
# string is not having any 
# dots nor any colons so 
# it is not a valid ip address 
return "Neither"
/**
 * @param {string} IP
 * @return {string}
 */
var validIPAddress = function(IP) {
    //check if IP is IPv4
    if(IP.split('.').length === 4){
        //split IP into octets
        let octets = IP.split('.');
        //check each octet
        for(let i = 0; i < octets.length; i++){
            //if octet is empty or longer than 3 characters, it's invalid
            if(octets[i].length === 0 || octets[i].length > 3){
                return "Neither";
            }
            //if octet starts with 0 and is longer than 1 character, it's invalid
            if(octets[i].charAt(0) === "0" && octets[i].length > 1){
                return "Neither";
            }
            //convert octet to number
            let octetNum = Number(octets[i]);
            //if octet is NaN or is less than 0 or greater than 255, it's invalid
            if(isNaN(octetNum) || octetNum < 0 || octetNum > 255){
                return "Neither";
            }
        }
        //if we get to this point, IP is valid IPv4
        return "IPv4";
    }
    //check if IP is IPv6
    else if(IP.split(':').length === 8){
        //split IP into hextets
        let hextets = IP.split(':');
        //check each hextet
        for(let i = 0; i < hextets.length; i++){
            //if hextet is empty or longer than 4 characters, it's invalid
            if(hextets[i].length === 0 || hextets[i].length > 4){
                return "Neither";
            }
            //convert hextet to number
            let hextetNum = Number(hextets[i]);
            //if hextet is NaN or is less than 0 or greater than 65535, it's invalid
            if(isNaN(hextetNum) || hextetNum < 0 || hextetNum > 65535){
                return "Neither";
            }
        }
        //if we get to this point, IP is valid IPv6
        return "IPv6";
    }
    //if IP is neither IPv4 nor IPv6, it's invalid
    else{
        return "Neither";
    }
};
class Solution {
public:
    bool isValidIP(string IP) {
        // check for empty string
        if (IP.empty()) {
            return false;
        }
        
        // check for correct number of dots
        int count = 0;
        for (int i = 0; i < IP.size(); i++) {
            if (IP[i] == '.') {
                count++;
            }
        }
        if (count != 3) {
            return false;
        }
        
        // check for correct number of characters in each section
        int section = 0;
        int numChars = 0;
        for (int i = 0; i < IP.size(); i++) {
            if (IP[i] == '.') {
                // check if current section is empty
                if (numChars == 0) {
                    return false;
                }
                // check if current section has more than 3 characters
                if (numChars > 3) {
                    return false;
                }
                // check if current section starts with 0 but has more than 1 character
                if (numChars > 1 && IP[i-numChars] == '0') {
                    return false;
                }
                // check if current section is greater than 255
                int sectionVal = stoi(IP.substr(i-numChars, numChars));
                if (sectionVal > 255) {
                    return false;
                }
                // reset for next section
                numChars = 0;
                section++;
            } else {
                numChars++;
            }
        }
        
        // check if final section is empty
        if (numChars == 0) {
            return false;
        }
        // check if final section has more than 3 characters
        if (numChars > 3) {
            return false;
        }
        // check if final section starts with 0 but has more than 1 character
        if (numChars > 1 && IP[IP.size()-numChars] == '0') {
            return false;
        }
        // check if final section is greater than 255
        int sectionVal = stoi(IP.substr(IP.size()-numChars, numChars));
        if (sectionVal > 255) {
            return false;
        }
        
        return true;
    }
};
using System;
using System.Text.RegularExpressions;

public class Solution {
    public string ValidIPAddress(string IP) {
        if (IsValidIPv4(IP)) return "IPv4";
        else if (IsValidIPv6(IP)) return "IPv6";
        else return "Neither";
    }
    
    public bool IsValidIPv4(string ip) {
        if (string.IsNullOrEmpty(ip)) return false;
        string[] tokens = ip.Split('.');
        if (tokens.Length != 4) return false;
        foreach (string token in tokens) {
            if (!IsValidIPv4Token(token)) return false;
        }
        return true;
    }
    
    public bool IsValidIPv4Token(string token) {
        if (string.IsNullOrEmpty(token)) return false;
        if (token.StartsWith("0") && token.Length > 1) return false;
        try {
            int parsedInt = int.Parse(token);
            if (parsedInt < 0 || parsedInt > 255) return false;
            if (parsedInt == 0 && token.Length > 1) return false;
        } catch (FormatException) {
            return false;
        }
        return true;
    }
    
    public bool IsValidIPv6(string ip) {
        if (string.IsNullOrEmpty(ip)) return false;
        string[] tokens = ip.Split(':');
        if (tokens.Length != 8) return false;
        foreach (string token in tokens) {
            if (!IsValidIPv6Token(token)) return false;
        }
        return true;
    }
    
    public bool IsValidIPv6Token(string token) {
        if (string.IsNullOrEmpty(token)) return false;
        token = token.ToLowerInvariant();
        int length = token.Length;
        if (length > 4) return false;
        foreach (char c in token) {
            bool isDigit = c >= '0' && c <= '9';
            bool isAlpha = c >= 'a' && c <= 'f';
            if (!(isDigit || isAlpha)) return false;
        }
        return true;
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]