Program to validate an IP address
Write a program to Validate an IP Address. An IP address is a unique identifier for devices on a network, enabling internet communication. It has two versions: IPv4 and IPv6. We will validate IPv4 and IPv6 addresses separately.
Table of Content
IPv4 Addresses Validation
IPv4 addresses use dot-decimal notation, consisting of four numbers (0-255) separated by dots, e.g., 172.16.254.1.
Example
Input: ip1 = "128.0.0.1";
Output: Valid
Explantaion: Each section split by '.' contains only digits, has no leading zeros, and lies within the range 0-255.Input: ip2 = "125.16.100.1";
Output: Valid
Explanation: Each section split by '.' contains only digits, has no leading zeros, and lies within the range 0-255.Input: ip3 = "125.512.100.1";
Output: Invalid
Explanation: Each section must be within the range 0-255, but 512 exceeds this limit, making the IP invalid.Input: ip4 = "125.512.100.abc"
Output: Invalid
Explanation: Each section must contain only numeric values, but "abc" is not a valid integer, making the IP invalid.
[Naive Approach] Using the Inbulit Library Methods - O(n) Time and O(n) Space
We use built-in library methods like
split()
in Python and Java, andstringstream
in C++ to split the string by.
. Then, we check if each segment lies within the range0-255
. If all segments satisfy this condition, it is a valid IPv4 address; otherwise, it is not.
#include <bits/stdc++.h>
using namespace std;
int isValid(string &s)
{
int n = s.size();
if (n < 7)
return false;
// Using string stream to separate all the string from
// '.' and push back into vector like for ex -
vector<string> v;
stringstream ss(s);
while (ss.good())
{
string substr;
getline(ss, substr, '.');
v.push_back(substr);
}
if (v.size() != 4)
return false;
// Iterating over the generated vector of strings
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;
}
// And lastly we are checking if the number is
// greater than 255 or not
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";
isValid(s1) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(s2) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(s3) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(s4) ? cout << "Valid\n" : cout << "Not valid\n";
return 0;
}
import java.util.StringTokenizer;
class GfG {
static boolean isValid(String s)
{
int n = s.length();
if (n < 7)
return false;
// Using StringTokenizer to separate all the strings
// from '.' and push back into vector like for example -
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 (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 (count != 4)
return false;
return true;
}
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(isValid(s1) ? "Valid"
: "Not valid");
System.out.println(isValid(s2) ? "Valid"
: "Not valid");
System.out.println(isValid(s3) ? "Valid"
: "Not valid");
System.out.println(isValid(s4) ? "Valid"
: "Not valid");
}
}
def isValid(s):
n = len(s)
if n < 7:
return False
# Using split to separate all the strings from '.'
# and create a list like for example -
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
s1 = "128.0.0.1"
s2 = "125.16.100.1"
s3 = "125.512.100.1"
s4 = "125.512.100.abc"
print("Valid" if isValid(s1) else "Not valid")
print("Valid" if isValid(s2) else "Not valid")
print("Valid" if isValid(s3) else "Not valid")
print("Valid" if isValid(s4) else "Not valid")
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class GfG {
static bool IsValidIP(string s)
{
int n = s.Length;
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;
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];
if (temp.Length > 1 && temp[0] == '0')
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;
}
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");
}
}
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;
}
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");
Output
Valid Valid Not valid Not valid
[Expected Approach] Using Traversal over the IP String - O(n) Time and O(1) Space
Iterate through the given string, extracting each section separated by
.
. Check if each section consists only of numeric characters and falls within the range 0-255. If any section fails these conditions, return "Invalid"; otherwise, return "Valid."
#include <bits/stdc++.h>
using namespace std;
bool valid_part(string &s)
{
int n = s.length();
// Length must be between 1 and 3
if (n == 0 || n > 3)
return false;
// Check if all characters are digits
for (char c : s)
{
if (c < '0' || c > '9')
return false;
}
// Prevent numbers like "00", "01"
if (s[0] == '0' && n > 1)
return false;
// Convert to integer manually
int num = 0;
for (char c : s)
{
num = num * 10 + (c - '0');
}
return num >= 0 && num <= 255;
}
// Function to check if a given string is a valid IPv4 address
bool isValid(const string &ip)
{
istringstream ss(ip);
string part;
int segmentCount = 0;
while (getline(ss, part, '.'))
{
if (!valid_part(part))
return false;
segmentCount++;
}
return segmentCount == 4;
}
int main()
{
string ip1 = "128.0.0.1";
string ip2 = "125.16.100.1";
string ip3 = "125.512.100.1";
string ip4 = "125.512.100.abc";
cout << (isValid(ip1) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip2) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip3) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip4) ? "Valid\n" : "Not valid\n");
return 0;
}
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool valid_part(char s[])
{
int len = strlen(s);
if (len == 0 || len > 3)
return false;
// Check if all characters are digits
for (int i = 0; i < len; i++)
{
if (!isdigit(s[i]))
return false;
}
// Convert to number and validate range
int num = 0;
for (int i = 0; i < len; i++)
{
num = num * 10 + (s[i] - '0');
}
return (num >= 0 && num <= 255) && !(s[0] == '0' && len > 1);
}
bool isValid(char ip[])
{
int len = strlen(ip);
if (len == 0)
return false;
char segment[4];
int segIndex = 0, segCount = 0;
for (int i = 0; i <= len; i++)
{
if (ip[i] == '.' || ip[i] == '\0')
{
if (segIndex == 0)
return false;
segment[segIndex] = '\0';
if (!valid_part(segment))
return false;
segIndex = 0;
segCount++;
}
else if (isdigit(ip[i]))
{
if (segIndex >= 3)
return false;
segment[segIndex++] = ip[i];
}
else
{
return false;
}
}
return segCount == 4;
}
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";
printf("%s\n", isValid(ip1) ? "Valid" : "Not valid");
printf("%s\n", isValid(ip2) ? "Valid" : "Not valid");
printf("%s\n", isValid(ip3) ? "Valid" : "Not valid");
printf("%s\n", isValid(ip4) ? "Valid" : "Not valid");
return 0;
}
import java.util.StringTokenizer;
public class GfG {
static boolean isValidPart(String s)
{
int n = s.length();
if (n > 3)
return false;
for (int i = 0; i < n; i++)
if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
return false;
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;
}
}
static int isValid(String ipStr)
{
// If the empty string then return false
if (ipStr == null)
return 0;
int dots = 0;
int len = ipStr.length();
int count = 0;
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, ".");
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;
}
if (dots != 3)
return 0;
return 1;
}
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(isValid(ip1) == 1 ? "Valid"
: "Not valid");
System.out.println(isValid(ip2) == 1 ? "Valid"
: "Not valid");
System.out.println(isValid(ip3) == 1 ? "Valid"
: "Not valid");
System.out.println(isValid(ip4) == 1 ? "Valid"
: "Not valid");
}
}
def valid_part(s):
n = len(s)
if n == 0 or n > 3:
return False
if not s.isdigit():
return False
if s[0] == '0' and n > 1:
return False
num = int(s)
return 0 <= num <= 255
def isValid(ip):
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not valid_part(part):
return False
return True
ip1 = "128.0.0.1"
ip2 = "125.16.100.1"
ip3 = "125.512.100.1"
ip4 = "125.512.100.abc"
print("Valid" if isValid(ip1) else "Not valid")
print("Valid" if isValid(ip2) else "Not valid")
print("Valid" if isValid(ip3) else "Not valid")
print("Valid" if isValid(ip4) else "Not valid")
using System;
using System.Text.RegularExpressions;
class GfG {
static bool ValidPart(string s)
{
int n = s.Length;
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 (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;
}
static int IsValidIP(string ipStr)
{
if (ipStr == null)
return 0;
int count = 0;
int len = ipStr.Length;
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");
}
}
function validPart(s)
{
const n = s.length;
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 isValid(ipStr)
{
// If the string is empty, return false
if (ipStr === null) {
return false;
}
const parts = ipStr.split(".");
let count = 0;
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;
}
const ip1 = "128.0.0.1";
const ip2 = "125.16.100.1";
const ip3 = "125.512.100.1";
const ip4 = "125.512.100.abc";
isValid(ip1) ? console.log("Valid")
: console.log("Not valid");
isValid(ip2) ? console.log("Valid")
: console.log("Not valid");
isValid(ip3) ? console.log("Valid")
: console.log("Not valid");
isValid(ip4) ? console.log("Valid")
: console.log("Not valid");
Output
Valid Valid Not valid Not valid
IPv6 Addresses Validation
IPv6 addresses use hexadecimal colon notation, with eight groups of four hex digits (0-9, A-F) separated by colons, e.g., 2001:db8:85a3::8a2e:370:7334.
Examples
Input: ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
Output: Valid
Explanation: Each section split by:
contains only hexadecimal digits (0-9, a-f, A-F) and is within the valid length of 1 to 4 characters.Input: ip2 = "FE80::1";
Output: InValid
Explanation: The IPv6 address not have 8 section.Input: ip3 = "2001:85a3::8a2e:0370:733400";
Output: Invalid
Explanation: Each section must be between 1 to 4 hexadecimal characters, but "733400" exceeds this limit, making the IP invalid.Input: ip4 = "2001:GHI8:85a3:0000:0000:8a2e:0370:7334";
Output: Invalid
Explanation: Each section must contain only valid hexadecimal characters (0-9, a-f, A-F), but "GHI8" includes invalid characters, making the IP invalid.
[Naive Approach] Using the Inbulit Library Methods - O(n) Time and O(n) Space
The approach splits the IPv6 address into segments using built-in functions (e.g.,
split
in Python/Java,stringstream
in C++). Each segment is checked to ensure it contains only valid hexadecimal characters (0-9, a-f, A-F) and is between 1 to 4 characters long. If the total segments are not exactly 8, or any segment is invalid, the IPv6 address is considered invalid.
#include <bits/stdc++.h>
using namespace std;
bool isValid(string &s)
{
int n = s.size();
if (n < 15)
return false;
vector<string> v;
stringstream ss(s);
while (ss.good())
{
string substr;
getline(ss, substr, ':');
v.push_back(substr);
}
if (v.size() != 8)
return false;
for (int i = 0; i < v.size(); i++)
{
string temp = v[i];
if (temp.empty() || temp.size() > 4)
return false;
for (char c : temp)
{
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))
return false;
}
}
return true;
}
int main()
{
string ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
string ip2 = "fe80::1";
string ip3 = "2001:db8:85a3::8a2e:370:7334";
string ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
isValid(ip1) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(ip2) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(ip3) ? cout << "Valid\n" : cout << "Not valid\n";
isValid(ip4) ? cout << "Valid\n" : cout << "Not valid\n";
return 0;
}
import java.util.*;
class GfG {
static boolean isValid(String s)
{
if (s.length() < 15)
return false;
String[] parts = s.split(":");
if (parts.length != 8)
return false;
for (String part : parts) {
if (part.isEmpty() || part.length() > 4)
return false;
for (char c : part.toCharArray()) {
if (!((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F')))
return false;
}
}
return true;
}
public static void main(String[] args)
{
String ip1
= "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String ip2 = "fe80::1";
String ip3 = "2001:db8:85a3::8a2e:370:7334";
String ip4
= "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
System.out.println(isValid(ip1) ? "Valid"
: "Not valid");
System.out.println(isValid(ip2) ? "Valid"
: "Not valid");
System.out.println(isValid(ip3) ? "Valid"
: "Not valid");
System.out.println(isValid(ip4) ? "Valid"
: "Not valid");
}
}
def isValid(s):
if len(s) < 15:
return False
parts = s.split(":")
if len(parts) != 8:
return False
for part in parts:
if len(part) == 0 or len(part) > 4:
return False
for c in part:
if not (c.isdigit() or 'a' <= c <= 'f' or 'A' <= c <= 'F'):
return False
return True
ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
ip2 = "fe80::1"
ip3 = "2001:db8:85a3::8a2e:370:7334"
ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334"
print("Valid" if isValid(ip1) else "Not valid")
print("Valid" if isValid(ip2) else "Not valid")
print("Valid" if isValid(ip3) else "Not valid")
print("Valid" if isValid(ip4) else "Not valid")
using System;
class GfG {
static bool isValid(string s)
{
if (s.Length < 15)
return false;
string[] parts = s.Split(':');
if (parts.Length != 8)
return false;
foreach(string part in parts)
{
if (part.Length == 0 || part.Length > 4)
return false;
foreach(char c in part)
{
if (!((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F')))
return false;
}
}
return true;
}
static void Main()
{
string ip1
= "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
string ip2 = "fe80::1";
string ip3 = "2001:db8:85a3::8a2e:370:7334";
string ip4
= "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
Console.WriteLine(isValid(ip1) ? "Valid"
: "Not valid");
Console.WriteLine(isValid(ip2) ? "Valid"
: "Not valid");
Console.WriteLine(isValid(ip3) ? "Valid"
: "Not valid");
Console.WriteLine(isValid(ip4) ? "Valid"
: "Not valid");
}
}
function isValid(s)
{
if (s.length < 15)
return false;
let parts = s.split(":");
if (parts.length !== 8)
return false;
for (let part of parts) {
if (part.length === 0 || part.length > 4)
return false;
for (let c of part) {
if (!((c >= "0" && c <= "9")
|| (c >= "a" && c <= "f")
|| (c >= "A" && c <= "F")))
return false;
}
}
return true;
}
let ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
let ip2 = "fe80::1";
let ip3 = "2001:db8:85a3::8a2e:370:7334";
let ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
console.log(isValid(ip1) ? "Valid" : "Not valid");
console.log(isValid(ip2) ? "Valid" : "Not valid");
console.log(isValid(ip3) ? "Valid" : "Not valid");
console.log(isValid(ip4) ? "Valid" : "Not valid");
Output
Valid Not valid Not valid Not valid
[Expected Approach] Using Traversal over the IP string - O(n) Time and O(1) Space
Iterate through the given string, split the string by ':', ensuring it has 8 sections. Verify each section contains only hexadecimal characters (0-9, a-f, A-F) and is 1-4 characters long. Return 'Valid' if all conditions are met; otherwise, return 'Invalid'."
#include <bits/stdc++.h>
using namespace std;
bool isValidSegment(string &s)
{
int n = s.length();
// Length must be between 1 and 4
if (n == 0 || n > 4)
return false;
// Check if all characters are valid hexadecimal digits
for (char c : s)
{
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))
return false;
}
return true;
}
// Function to check if a given string is a valid IPv6 address
bool isValid( string &ip)
{
int colonCount = 0;
int len = ip.length();
// Count the number of colons
for (char c : ip)
{
if (c == ':')
colonCount++;
}
// An IPv6 address must have exactly 7 colons
if (colonCount != 7)
return false;
// Split manually by ':'
string segment;
int segmentCount = 0;
for (int i = 0; i < len; i++)
{
if (ip[i] == ':')
{
if (!isValidSegment(segment))
return false;
segment.clear();
segmentCount++;
}
else
{
segment += ip[i];
}
}
if (!isValidSegment(segment))
return false;
return segmentCount == 7;
}
int main()
{
string ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
string ip2 = "fe80::1";
string ip3 = "2001:db8:85a3::8a2e:370:7334";
string ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
cout << (isValid(ip1) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip2) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip3) ? "Valid\n" : "Not valid\n");
cout << (isValid(ip4) ? "Valid\n" : "Not valid\n");
return 0;
}
import java.util.*;
public class GfG {
public static boolean isValidSegment(String s) {
int n = s.length();
if (n == 0 || n > 4) return false;
for (char c : s.toCharArray()) {
// Only hexadecimal characters allowed
if (!Character.isDigit(c) && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) {
return false;
}
}
return true;
}
public static boolean isValid(String ip) {
if (ip == null || ip.isEmpty()) return false;
String[] segments = ip.split(":");
// IPv6 must have exactly 8 segments
if (segments.length != 8) return false;
for (String segment : segments) {
if (!isValidSegment(segment)) return false;
}
return true;
}
public static void main(String[] args) {
String ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String ip2 = "fe80::1";
String ip3 = "2001:db8:85a3::8a2e:370:7334";
String ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
System.out.println((isValid(ip1) ? "Valid" : "Not valid"));
System.out.println((isValid(ip2) ? "Valid" : "Not valid"));
System.out.println((isValid(ip3) ? "Valid" : "Not valid"));
System.out.println((isValid(ip4) ? "Valid" : "Not valid"));
}
}
def is_valid_segment(segment):
if not (1 <= len(segment) <= 4):
return False
for char in segment:
# Only hexadecimal characters allowed
if not (char.isdigit() or 'a' <= char.lower() <= 'f'):
return False
return True
def isValid(ip):
if not ip:
return False
segments = ip.split(":")
# IPv6 must have exactly 8 segments
if len(segments) != 8:
return False
return all(is_valid_segment(segment) for segment in segments)
# Test cases
ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
ip2 = "fe80::1"
ip3 = "2001:db8:85a3::8a2e:370:7334"
ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334"
print(f"{'Valid' if isValid(ip1) else 'Not valid'}")
print(f"{'Valid' if isValid(ip2) else 'Not valid'}")
print(f"{'Valid' if isValid(ip3) else 'Not valid'}")
print(f"{'Valid' if isValid(ip4) else 'Not valid'}")
using System;
class GfG {
static bool IsValidSegment(string s)
{
int n = s.Length;
if (n == 0 || n > 4)
return false;
foreach(char c in s)
{
if (!((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F')))
return false;
}
return true;
}
static bool IsValid(string ip)
{
int colonCount = 0;
int len = ip.Length;
foreach(char c in ip)
{
if (c == ':')
colonCount++;
}
if (colonCount != 7)
return false;
string segment = "";
int segmentCount = 0;
for (int i = 0; i < len; i++) {
if (ip[i] == ':') {
if (!IsValidSegment(segment))
return false;
segment = "";
segmentCount++;
}
else {
segment += ip[i];
}
}
if (!IsValidSegment(segment))
return false;
return segmentCount == 7;
}
static void Main()
{
string ip1
= "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
string ip2 = "fe80::1";
string ip3 = "2001:db8:85a3::8a2e:370:7334";
string ip4
= "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
Console.WriteLine(IsValid(ip1) ? "Valid"
: "Not valid");
Console.WriteLine(IsValid(ip2) ? "Valid"
: "Not valid");
Console.WriteLine(IsValid(ip3) ? "Valid"
: "Not valid");
Console.WriteLine(IsValid(ip4) ? "Valid"
: "Not valid");
}
}
function isValidSegment(s)
{
const n = s.length;
if (n === 0 || n > 4) {
return false;
}
for (let i = 0; i < n; i++) {
const c = s[i];
if (!((c >= "0" && c <= "9")
|| (c >= "a" && c <= "f")
|| (c >= "A" && c <= "F"))) {
return false;
}
}
return true;
}
function isValid(ip)
{
let colonCount = 0;
const len = ip.length;
for (let i = 0; i < len; i++) {
if (ip[i] === ":") {
colonCount++;
}
}
if (colonCount !== 7) {
return false;
}
let segment = "";
let segmentCount = 0;
for (let i = 0; i < len; i++) {
if (ip[i] === ":") {
if (!isValidSegment(segment)) {
return false;
}
segment = "";
segmentCount++;
}
else {
segment += ip[i];
}
}
if (!isValidSegment(segment)) {
return false;
}
return segmentCount === 7;
}
const ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
const ip2 = "fe80::1";
const ip3 = "2001:db8:85a3::8a2e:370:7334";
const ip4 = "2001:0db8:85a3:xyz:0000:8a2e:0370:7334";
console.log(isValid(ip1) ? "Valid" : "Not valid");
console.log(isValid(ip2) ? "Valid" : "Not valid");
console.log(isValid(ip3) ? "Valid" : "Not valid");
console.log(isValid(ip4) ? "Valid" : "Not valid");
Output
Valid Not valid Not valid Not valid