Validate IPv4 address in Java

JavaIp Address

Java Problem Overview


I want to validate an IPv4 address using Java. It should be written using the dot-decimal notation, so it should have 3 dots ("."), no characters, numbers in between the dots, and numbers should be in a valid range. How should it be done?

Java Solutions


Solution 1 - Java

Pretty simple with Regular Expression (but note this is much less efficient and much harder to read than worpet's answer that uses an Apache Commons Utility)

private static final Pattern PATTERN = Pattern.compile(
		"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

public static boolean validate(final String ip) {
	return PATTERN.matcher(ip).matches();
}

Based on post Mkyong

Solution 2 - Java

Solution 3 - Java

Use Guava's

InetAddresses.isInetAddress(ipStr)
  

Solution 4 - Java

Please see https://stackoverflow.com/a/5668971/1586965 which uses an apache commons library InetAddressValidator

Or you can use this function -

public static boolean validate(final String ip) {
	String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";

	return ip.matches(PATTERN);
}

Solution 5 - Java

You can use a regex, like this:

(([0-1]?[0-9]{1,2}\.)|(2[0-4][0-9]\.)|(25[0-5]\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))

This one validates the values are within range.

Android has support for regular expressions. See java.util.regex.Pattern.

class ValidateIPV4
{

   static private final String IPV4_REGEX = "(([0-1]?[0-9]{1,2}\\.)|(2[0-4][0-9]\\.)|(25[0-5]\\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))";
   static private Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);

   public static boolean isValidIPV4(final String s)
   {          
      return IPV4_PATTERN.matcher(s).matches();
   }
}

To avoid recompiling the pattern over and over, it's best to place the Pattern.compile() call so that it is executed only once.

Solution 6 - Java

There is also an undocumented utility class sun.net.util.IPAddressUtil, which you should not actually use, although it might be useful in a quick one-off, throw-away utility:

boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);

Internally, this is the utility class InetAddress uses to parse IP addresses.

Note that this will return true for strings like "123", which, technically are valid IPv4 addresses, just not in dot-decimal notation.

Solution 7 - Java

This is for Android, testing for IPv4 and IPv6

Note: the commonly used InetAddressUtils is deprecated. Use new InetAddress classes

public static Boolean isIPv4Address(String address) {
    if (address.isEmpty()) {
        return false;
    }
    try {
        Object res = InetAddress.getByName(address);
        return res instanceof Inet4Address || res instanceof Inet6Address;
    } catch (final UnknownHostException exception) {
        return false;
    }
}

Solution 8 - Java

The IPAddress Java library will do it. The javadoc is available at the link. Disclaimer: I am the project manager.

This library supports IPv4 and IPv6 transparently, so validating either works the same below, and it also supports CIDR subnets as well.

Verify if an address is valid

    String str = "1.2.3.4";
    IPAddressString addrString = new IPAddressString(str);
    try {
         IPAddress addr = addrString.toAddress();
         ...
    } catch(AddressStringException e) {
        //e.getMessage provides validation issue
    }

Solution 9 - Java

Write up a suitable regular expression and validate it against that. The JVM have full support for regular expressions.

Solution 10 - Java

If it is IP4, you can use a regular expression as follows:

^(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)\\.){3}(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)$.

Solution 11 - Java

There are so many ways to achieve that,but regular expression is more efficient.

Look at the code below:

public static void main(String[] args) {

	String ipStr1 = "255.245.188.123"; // valid IP address
	String ipStr2 = "255.245.188.273"; // invalid IP address - 273 is greater than 255

	validateIP(ipStr1);
	validateIP(ipStr2);
}

public static void validateIP(String ipStr) {
	String regex = "\\b((25[0–5]|2[0–4]\\d|[01]?\\d\\d?)(\\.)){3}(25[0–5]|2[0–4]\\d|[01]?\\d\\d?)\\b";
	System.out.println(ipStr + " is valid? " + Pattern.matches(regex, ipStr));
}

Solution 12 - Java

Regular Expression is the most efficient way to solve this problem. Look at the code below. Along validity, it also checks IP address class in which it belongs and whether it is reserved IP Address or not

Pattern ipPattern;
int[] arr=new int[4];
int i=0;

//Method to check validity
 private String validateIpAddress(String ipAddress) {
	  Matcher ipMatcher=ipPattern.matcher(ipAddress);
	  
	    //Condition to check input IP format
	    if(ipMatcher.matches()) {       
		  
		   //Split input IP Address on basis of .
		   String[] octate=ipAddress.split("[.]");     
		   for(String x:octate) { 
			 
			  //Convert String number into integer
			  arr[i]=Integer.parseInt(x);             
			  i++;
		 }
		 
		//Check whether input is Class A IP Address or not
		 if(arr[0]<=127) {                          
			 if(arr[0]==0||arr[0]==127)
			   	 return(" is Reserved IP Address of Class A");
			 else if(arr[1]==0&&arr[2]==0&&arr[3]==0)
			     return(" is Class A Network address");
			 else if(arr[1]==255&&arr[2]==255&&arr[3]==255)
		         return( " is Class A Broadcast address");
	         else 
	        	 return(" is valid IP Address of Class A");
		 }
		 
		//Check whether input is Class B IP Address or not
		 else if(arr[0]>=128&&arr[0]<=191) {        
			 if(arr[2]==0&&arr[3]==0)
		         return(" is Class B Network address");
	         else if(arr[2]==255&&arr[3]==255)
		         return(" is Class B Broadcast address");
	         else
			     return(" is valid IP Address of Class B");
		 }
		 
		//Check whether input is Class C IP Address or not
		 else if(arr[0]>=192&&arr[0]<=223) {        
			 if(arr[3]==0)
				 return(" is Class C Network address");
	         else if(arr[3]==255)
	        	 return(" is Class C Broadcast address");
	         else
	        	 return( " is valid IP Address of Class C");
		}
		 
		//Check whether input is Class D IP Address or not
		else if(arr[0]>=224&&arr[0]<=239) {          
			 return(" is Class D IP Address Reserved for multicasting");
		}
		 
		//Execute if input is Class E IP Address
		else  {                                   
			 return(" is Class E IP Address Reserved for Research and Development by DOD");
        }
		
    }
	  
	//Input not matched with IP Address pattern
	else                                     
		return(" is Invalid IP Address");
	
	
}


public static void main(String[] args) {
	
	Scanner scan= new Scanner(System.in);
	System.out.println("Enter IP Address: ");
	
	//Input IP Address from user
	String ipAddress=scan.nextLine();  
	scan.close();
	IPAddress obj=new IPAddress();
	
	//Regex for IP Address
	obj.ipPattern=Pattern.compile("((([0-1]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([0-1]?\\d\\d?|2[0-4]\\d|25[0-5]))");
	
	//Display output
	System.out.println(ipAddress+ obj.validateIpAddress(ipAddress));

}

Solution 13 - Java

Get the valid ip address in two lines using Regular Expression Please check the comment session of code how the regular expression works to get the number range.

public class regexTest {


    public static void main(String[] args) {
        String IP = "255.001.001.255";
        System.out.println(IP.matches(new MyRegex().pattern));
    }

    }
    
    /*
    * /d - stands for any number between 0 to 9
    * /d{1,2} - preceding number that 0 to 9 here , can be of 1 digit to 2 digit . so minimum 0 and maximum 99
    * |  this stands for or operator
    *
    * () this is applied on a group to get the single value of outcome
    * (0|1)\d{2} = first digit is either 0 or 1 and other two digits can be any number between ( 0 to 9)
    * 2[0-4]\d - first digit is 2 , second digit can be between 0 to 4 and last digit can be 0 to 9
    * 25[0-5] - first two digit will be 25 and last digit will be between 0 to 5
    *
    * */
    class MyRegex {

        String zeroTo255 = "(\\d{1,2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])";
        public String pattern =  zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255;;

    }

Solution 14 - Java

Please have a look into IPAddressUtil OOTB class present in sun.net.util ,that should help you.

Solution 15 - Java

If you don care about the range, the following expression will be useful to validate from 1.1.1.1 to 999.999.999.999

"[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}"

Solution 16 - Java

public static boolean isIpv4(String ipAddress) {
	if (ipAddress == null) {
		return false;
	}
    String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
    Pattern pattern = Pattern.compile(ip);
    Matcher matcher = pattern.matcher(ipAddress);
    return matcher.matches();
}

Solution 17 - Java

/**
 * Check if ip is valid
 *
 * @param ip to be checked
 * @return <tt>true</tt> if <tt>ip</tt> is valid, otherwise <tt>false</tt>
 */
private static boolean isValid(String ip) {
    String[] bits = ip.split("\\.");
    if (bits.length != 4) {
        return false;
    }
    for (String bit : bits) {
        try {
            if (Integer.valueOf(bit) < 0 || Integer.valueOf(bit) > 255) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false; /* contains other other character */
        }
    }
    return true;
}

Solution 18 - Java

the lib of apache-httpcomponents

// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));

maven lib (update Sep, 2019)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

Solution 19 - Java

my solution (supports leading 0s):

   String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";

Solution 20 - Java

 private static final String IPV4_PATTERN_ALLOW_LEADING_ZERO =
            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

Solution 21 - Java

private static boolean findValidIP(String ipAddress) {
        String[] ipAddressSplited = ipAddress.split("\\.");
        int correctFragments = 0;

        for (String ctr : ipAddressSplited) {
            int value = -10;
            try {
                value = Integer.parseInt(ctr);
            } catch (NumberFormatException exception) {
                value = -1;
            }

            if (value >= 0 && value <= 255 && ipAddressSplited.length == 4) correctFragments++;
        }

        System.out.println(correctFragments == 4 ? "Valid IP Address - " + ipAddress : "Invalid IP Address - " + ipAddress);
        return correctFragments == 4;
    }

Solution 22 - Java

I write a regex to validate IPv4.
You can refer to my solution.

import java.util.Scanner;

/**
 * @author ManhKM on 11/26/2021
 * @project java-core-v1.0
 */
public class ValidateIPv4 {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String IP = in.next();
            System.out.println(IP.matches(new MyRegex().pattern));
        }

    }
}

class MyRegex{

    String pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
}

Solution 23 - Java

public void setIpAddress(String ipAddress) { if(ipAddress.matches("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")) //regular expression for ipv4 this.ipAddress = ipAddress; else System.out.println("incorrect IpAddress"); }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniRunnerView Question on Stackoverflow
Solution 1 - JavaNecronetView Answer on Stackoverflow
Solution 2 - JavaworpetView Answer on Stackoverflow
Solution 3 - JavawileyquixoteView Answer on Stackoverflow
Solution 4 - JavaAkarshit WalView Answer on Stackoverflow
Solution 5 - JavamdmaView Answer on Stackoverflow
Solution 6 - JavaJason CView Answer on Stackoverflow
Solution 7 - JavaPian0_M4nView Answer on Stackoverflow
Solution 8 - JavaSean FView Answer on Stackoverflow
Solution 9 - JavaThorbjørn Ravn AndersenView Answer on Stackoverflow
Solution 10 - JavakhachikView Answer on Stackoverflow
Solution 11 - Javauser5150135View Answer on Stackoverflow
Solution 12 - JavaDeepali AggView Answer on Stackoverflow
Solution 13 - JavaArpan SainiView Answer on Stackoverflow
Solution 14 - JavaGirishView Answer on Stackoverflow
Solution 15 - JavadarkconejaView Answer on Stackoverflow
Solution 16 - JavaveesonView Answer on Stackoverflow
Solution 17 - JavaduyuanchaoView Answer on Stackoverflow
Solution 18 - Javafo0View Answer on Stackoverflow
Solution 19 - JavaKurnianto TrilaksonoView Answer on Stackoverflow
Solution 20 - JavaRitu GuptaView Answer on Stackoverflow
Solution 21 - JavaViknesh TPKView Answer on Stackoverflow
Solution 22 - JavaManhKMView Answer on Stackoverflow
Solution 23 - JavaM Manzar AbBasView Answer on Stackoverflow