77

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?

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
iRunner
  • 1,472
  • 6
  • 25
  • 40
  • note that not all technically valid IP address notations have the three dots, only the dot notation of IP address has them. Note also ipv6, and you might or might not want to separate private address spaces from public. – eis Mar 24 '14 at 18:06
  • 4
    I think all the code reviewers in the world would be immensely grateful if you could change your accepted answer to worpet's answer :) – samthebest Aug 07 '14 at 18:53
  • @samthebest : Ohk. I asked this question long back and accepted the answer which worked for me that time. – iRunner Dec 18 '19 at 02:44
  • Thanks @iRunner that makes sense. Fortunately Stack Overflow does allow you to change the accepted answer and this does not incur any kind of penalty. The feature exists exactly for this kind of situation where a new and better answer comes along much later than the original answer. Please could you give it a try and accept Worpet's answer? – samthebest Dec 18 '19 at 12:27

22 Answers22

96

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

samthebest
  • 30,803
  • 25
  • 102
  • 142
Necronet
  • 6,704
  • 9
  • 49
  • 89
  • Ohhhh,its not Working on android.When application start it gives error of force close – iRunner Apr 14 '11 at 18:06
  • 6
    What about strangely-formatted IP addresses, like 127.1 (which is equivalent to 127.0.0.1)? What about IPv6? – krzysz00 Nov 29 '13 at 18:21
  • You can simply write: return ip != null && ip.matches(PATTERN) – Ramanqul Buzaubak Mar 16 '15 at 07:46
  • 2
    One potential problem with your regular expression is that it seems to match things like 010.020.030.040, but that can be problematic since numbers that start with 0 can often be interpreted as octal numbers. – Ron Maupin Jul 31 '15 at 21:11
  • 1
    Exactly! This misses the leading 0 case. @Akarshit Wal 's solution works better. – Tao Zhang Dec 11 '16 at 03:10
61

Try the InetAddressValidator utility class.

Docs here:

http://commons.apache.org/validator/apidocs/org/apache/commons/validator/routines/InetAddressValidator.html

Download here:

http://commons.apache.org/validator/

worpet
  • 3,788
  • 2
  • 31
  • 53
  • 17
    It is always better to use an already written utility for these things – Jaime Hablutzel Jul 25 '11 at 16:41
  • Warning: this will drag commons-logging into your classpath, which may have unintended side-effects. If you don't want that, you may prefer the Guava option below... – Tadhg Jan 04 '22 at 20:19
31

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);
}
samthebest
  • 30,803
  • 25
  • 102
  • 142
Akarshit Wal
  • 631
  • 6
  • 12
  • 3
    Thanks! This is the only one works for me. Other regex patterns all miss the cases with leading 0, which is illegal for IPv4. – Tao Zhang Dec 11 '16 at 03:07
25

Use Guava's

InetAddresses.isInetAddress(ipStr)
wileyquixote
  • 391
  • 3
  • 5
  • 1
    Actually there is `isInetAddress` method which returns true/false if address is valid. It's bit cleaner than checking for exception ;). – Pyro2266 Oct 23 '18 at 13:30
  • I've edited the post to update the link and switch to the more straightforward boolean-returning method, thanks! – wileyquixote Mar 25 '19 at 13:34
11

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.

Jason C
  • 38,729
  • 14
  • 126
  • 182
mdma
  • 56,943
  • 12
  • 94
  • 128
  • it will match "001.xxx.xxx.xxx". – khachik Apr 14 '11 at 17:57
  • I'm not sure, so posted an expression which explicitly restricts `0xx, 0x`. – khachik Apr 14 '11 at 18:05
  • 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]))";.this line is giving me errors :( – iRunner Apr 28 '11 at 18:12
  • @khachik A little late, but: That is a [valid IP address in dotted-decimal notation](http://tools.ietf.org/html/rfc1166). In fact, RFC1166 actually gives `128.009.000.032` as an example on page 5. – Jason C Mar 24 '14 at 17:46
  • Is it valid when there are 4 zeros?? http://stackoverflow.com/questions/25191349/is-an-ip-address-with-an-octet-given-by-4-or-more-zeros-a-valid-ip-address-e-g/25191350#25191350 – samthebest Aug 07 '14 at 20:14
7

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.

Jason C
  • 38,729
  • 14
  • 126
  • 182
3

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;
    }
}
Community
  • 1
  • 1
Pian0_M4n
  • 2,505
  • 31
  • 35
  • 2
    I don't think this does what the author requested. If you pass in InetAddress.getByName("google.com") you'll get true, this is because getByName resolves dns names to IP address. – Kevin Jun 22 '17 at 14:47
3

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
    }
Sean F
  • 4,344
  • 16
  • 30
1

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));
}
1

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));

}
1

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)$.

khachik
  • 28,112
  • 9
  • 59
  • 94
1

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;;

    }
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
0

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

Girish
  • 11
  • It is not recommended to use `sun.*` packages -> [detail](https://www.java-tips.org/java-se-tips-100019/24-java-lang/123-why-developers-should-not-write-programs-that-call-sun-packages.html) – buræquete Jul 03 '18 at 15:43
0

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}"
darkconeja
  • 348
  • 3
  • 7
0
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();
}
veeson
  • 195
  • 2
  • 6
0
/**
 * 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;
}
duyuanchao
  • 3,863
  • 1
  • 25
  • 16
0

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>
fo0
  • 186
  • 4
  • 12
0

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])?$";
0
 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])$";
Ritu Gupta
  • 2,249
  • 1
  • 18
  • 11
0
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;
    }
0

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]?)$";
}
ManhKM
  • 41
  • 3
-2

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"); }

  • 1
    Hi. You have rejected and undone helpful edits on your post by other users multiple times. If you do not like others to do format improvements for you please do them yourself. https://stackoverflow.com/editing-help Keeping the post in that unhelpful formatting is unlikely to be of any benefit to you. – Yunnosch May 28 '21 at 11:59