HackerRank IP Address Validation Solution

Hello Programmers, In this post, you will learn how to solve HackerRank IP Address Validation Solution. This problem is a part of the Regex HackerRank Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the  Regex HackerRank Solutions using  CPP, JAVA, PYTHON, JavaScript & PHP Programming Languages.

HackerRank IP Address Validation Solution
HackerRank IP Address Validation Solution

HackerRank IP Address Validation Solution

Problem

You will be provided with N lines of what are possibly IP addresses. You need to detect if the text contained in each of the lines represents an (a)IPv4 address (b)IPv6 address or (c)None of these.

IPv4 was the first publicly used Internet Protocol which used 4 byte addresses which permitted for 232 addresses. The typical format of an IPv4 address is A.B.C.D where A, B, C and D are Integers lying between 0 and 255 (both inclusive).

IPv6, with 128 bits was developed to permit the expansion of the address space. To quote from the linked article: The 128 bits of an IPv6 address are represented in 8 groups of 16 bits each. Each group is written as 4 hexadecimal digits and the groups are separated by colons (:). The address 2001:0db8:0000:0000:0000:ff00:0042:8329 is an example of this representation. Consecutive sections of zeros will be left as they are.
An IPv6 value such as “…:0:…” or “…:5:…” is address-wise identical to “...:0000:…” or “…:0005:….”. Leading zeros may be omitted in writing the address.

Input Format
An integer N such that N <= 50. This is followed by N lines such that each the text in each line is either an IPv4 address or an IPv6 address, or a chunk of text which does not equal either of these. There will be no extra text or whitespace leading or trailing the IP address in a line (if it is an IP address). The number of characters in each line will not exceed 500.

Output Format
N lines.
The ith output line should equal (a)IPv4 or (b)IPv6 or (c)Neither depending on what you detected the ith input line to be.

Sample Input

3
This line has junk text.
121.18.19.20
2001:0db8:0000:0000:0000:ff00:0042:8329

Sample Output

Neither
IPv4
IPv6

HackerRank IP Address Validation Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

bool ans4(string&s){
    int a=s.find(".");
    if(a==string::npos||a>3)return false;
    for(int i=0;i<a;i++){
        if(s[i]>'9'||s[i]<'0')return false;
    }
    int x1=0,y1=1;
    for(int i=a-1;i>=0;i--){x1+=y1*(s[i]-'0');y1*=10;}
    if(x1>255)return false;
    
    
    int b,c,d;
    b=s.find(".",a+1);
    if(b==string::npos||b-a>4)return false;
    for(int i=a+1;i<b;i++){
        if(s[i]>'9'||s[i]<'0')return false;
    }
    x1=0,y1=1;
    for(int i=b-1;i>a;i--){x1+=y1*(s[i]-'0');y1*=10;}
    if(x1>255)return false;
    
    
    
    c=s.find(".",b+1);
    if(c==string::npos||c-b>4)return false;
    for(int i=b+1;i<c;i++){
        if(s[i]>'9'||s[i]<'0')return false;
    }
    x1=0,y1=1;
    for(int i=c-1;i>b;i--){x1+=y1*(s[i]-'0');y1*=10;}
    if(x1>255)return false;
    
    for(int i=c+1;i<s.length()&&s[i]!=32;i++){
        if(s[i]>'9'||s[i]<'0')return false;
    }
    x1=0,y1=1;
    for(int i=s.length()-1;i>c;i--){
        if(s[i]!=32){
            x1+=y1*(s[i]-'0');y1*=10;
        }
    }
    if(x1>255)return false;
    return true;
}

bool ans6(string&s){
    int a1=s.find(":"),a2,a3,a4,a5,a6,a7;
    if(a1==string::npos||a1>4)return false;
    for(int i=0;i<a1;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a2=s.find(":",a1+1);
    if(a2==string::npos||a2-a1>5)return false;
    for(int i=a1+1;i<a2;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a3=s.find(":",a2+1);
    if(a3==string::npos||a3-a2>5)return false;
    //cout<<a3<<endl;
    for(int i=a2+1;i<a3;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a4=s.find(":",a3+1);
    if(a4==string::npos||a4-a3>5)return false;
    for(int i=a3+1;i<a4;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a5=s.find(":",a4+1);
    if(a5==string::npos||a5-a4>5)return false;
    for(int i=a4+1;i<a5;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a6=s.find(":",a5+1);
    if(a6==string::npos||a6-a5>5)return false;
    for(int i=a5+1;i<a6;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    a7=s.find(":",a6+1);
    if(a7==string::npos||a7-a6>5)return false;
    for(int i=a6+1;i<a7;i++){
        if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
        else return false;
    }
    for(int i=a7+1;i<s.length();i++){
        if(s[i]!=32){
            if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')){}
            else return false;
        }
    }
    return true;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int t;cin>>t;
    string s;
    getline(cin,s);
    while(t--){
        getline(cin,s);
        if(ans4(s))cout<<"IPv4"<<endl;
        else if(ans6(s))cout<<"IPv6"<<endl;
        else cout<<"Neither"<<endl;
    }
    return 0;
}

HackerRank IP Address Validation Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try{
            BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
            String s = sc.readLine();
            int n = Integer.parseInt(s);
            Pattern ipv4 = Pattern.compile("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
            Pattern ipv6 = Pattern.compile("(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))");
            Matcher m1,m2;
            for(int i=0;i<n;i++){
                    s=sc.readLine();
                    m1=ipv4.matcher(s);
                    m2=ipv6.matcher(s);
                    if (m1.matches())
                        System.out.println("IPv4");
                    else if(m2.matches())
                        System.out.println("IPv6");
                    else System.out.println("Neither");
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

HackerRank IP Address Validation Solution in Python

import sys
def check(ip):
    if '.' in ip:
        #ipv4
        ip = ip.split('.')
        if len(ip)!=4:
            return False
        for n in ip:
            try:
                n = int(n)
            except:
                return False
            else:
                if n > 255 or n < 0:
                    return False
        return 4
    elif ':' in ip:
        #ipv4
        ip = ip.split(':')
        if len(ip)!=8:
            return False
        for n in ip:
            for c in n:
                if (c not in map(str, range(10)) and
                    c not in map(lambda x: chr(x),range(ord('a'), ord('f')+1))):
                    return False
        return 6
    else:
        return False
n = int(sys.stdin.readline())
for _ in xrange(n):
    val = sys.stdin.readline().strip()
    res = check(val)
    if res == False:
        print "Neither"
    elif res == 4:
        print "IPv4"
    elif res == 6:
        print "IPv6"
    else:
        print "UFO"
    

HackerRank IP Address Validation Solution in JavaScript

function processData(input) {
    //Enter your code here
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
    inputArr = new Array();
    inputArr = _input.split("\n");
    NumOfInputs = inputArr[0];
    for(i = 1; i<=NumOfInputs; i++){
        ip = inputArr[i];
        ipv4 = /^([12]?[0-9]{1,2}\.){3}[12]?[0-9]{1,2}$/g.test(ip);
        if(ipv4){
            console.log("IPv4");
        }else{
            ipv6 = /^([0-9a-f]{1,4}\:){7}[0-9a-f]{1,4}$/g.test(ip);
            if(ipv6){
                console.log("IPv6");
            }else{
                console.log("Neither");
            }
        }
    }
    
});

process.stdin.on("end", function () {
   processData(_input);
});

HackerRank IP Address Validation Solution in PHP

<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$count = trim(fgets($_fp));
for($i=0;$i<$count;$i++)
{
    $line = trim(fgets($_fp));
    if(preg_match("/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/",$line))
        echo "IPv4\n";
    else if(preg_match("/^[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}\:[a-fA-F0-9]{1,4}$/",$line))
        echo "IPv6\n";
    else echo "Neither\n";
}
?>

Disclaimer: This problem (IP Address Validation) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

Sharing Is Caring