Program to validate an IP address
Last Updated : 15 Sep, 2025
Find whether a given IP address is valid. 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.
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: s = "128.0.0.1";
Output: true
Explantaion: Each section split by '.' contains only digits, has no leading zeros, and lies within the range 0-255.
Input: s = "125.16.100.1";
Output: true
Explanation: Each section split by '.' contains only digits, has no leading zeros, and lies within the range 0-255.
Input: s = "125.512.100.1";
Output: false
Explanation: Each section must be within the range 0-255, but 512 exceeds this limit, making the IP invalid.
Input: s = "125.512.100.abc"
Output: false
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, and stringstream
in C++ to split the string by .
. Then, we check if each segment lies within the range 0-255
. If all segments satisfy this condition, it is a valid IPv4 address; otherwise, it is not.
C++ #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 s = "128.0.0.1"; isValid(s) ? cout << "true" : cout << "false"; return 0; }
Java 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 s = "128.0.0.1"; System.out.println(isValid(s) ? "true": "false"); } }
Python 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 if __name__ == "__main__": s = "128.0.0.1" print("true" if isValid(s) else "false")
C# 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 s = "128.0.0.1"; Console.WriteLine(IsValidIP(s) ? "true": "false"); } }
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 s = "128.0.0.1"; isValidIP(s) ? console.log("true"): console.log("false");
[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 "false", otherwise, return "true."
C++ #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( 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 s = "128.0.0.1"; cout << (isValid(s) ? "true" : "false"); return 0; }
Java 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 s = "128.0.0.1"; System.out.println(isValid(s) == 1 ? "true": "false"); } }
Python 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) # The string is valid if the number # generated is between 0 to 255 return 0 <= num <= 255 def isValid(ip): # If the empty string then return false parts = ip.split('.') if len(parts) != 4: return False for part in parts: if not valid_part(part): return False return True if __name__ == "__main__": s = "128.0.0.1" print("true" if isValid(s) else "false")
C# 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 s = "128.0.0.1"; Console.WriteLine(IsValidIP(s) == 1 ? "true" : "false"); } }
Javascript 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; } // Driver Code const s = "128.0.0.1"; isValid(s) ? console.log("true"): console.log("false");
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: s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
Output: true
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: s = "FE80::1";
Output: false
Explanation: The IPv6 address not have 8 section.
Input: s = "2001:85a3::8a2e:0370:733400";
Output: false
Explanation: Each section must be between 1 to 4 hexadecimal characters, but "733400" exceeds this limit, making the IP invalid.
Input: s = "2001:GHI8:85a3:0000:0000:8a2e:0370:7334";
Output: false
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.
C++ #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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; isValid(s) ? cout << "true" : cout << "false"; return 0; }
Java 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; System.out.println(isValid(s) ? "true": "false"); } }
Python 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 if __name__ == "__main__": s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" print("true" if isValid(s) else "false")
C# 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; Console.WriteLine(isValid(s) ? "true": "false"); } }
JavaScript 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; console.log(isValid(s) ? "true" : "false");
[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 "true" if all conditions are met; otherwise, return 'false'.
C++ #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; } 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; cout << (isValid(s) ? "true" : "false"); return 0; }
Java 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; System.out.println((isValid(s) ? "true" : "false")); } }
Python 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) if __name__ == "__main__": s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" print(f"{'true' if isValid(s) else 'false'}")
C# 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; Console.WriteLine(IsValid(s) ? "true": "false"); } }
JavaScript 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 s = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; console.log(isValid(s) ? "true" : "false");
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem
My Profile