How to validate IP address with regular expression

IP Address Regular Expression Pattern

^([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])$

Description

^		#start of the line
 (		#  start of group #1
   [01]?\\d\\d? #    Can be one or two digits. If three digits appear, it must start either 0 or 1
		#    e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
    |		#    ...or
   2[0-4]\\d	#    start with 2, follow by 0-4 and end with any digit (2[0-4][0-9]) 
    |           #    ...or
   25[0-5]      #    start with 2, follow by 5 and ends with 0-5 (25[0-5]) 
 )		#  end of group #2
  \.            #  follow by a dot "."
....            # repeat with 3 times (3x)
$		#end of the line

Whole combination means, digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255″.

1. Java Regular Expression Example

IPAddressValidator.java
package com.mkyong.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class IPAddressValidator{
 
    private Pattern pattern;
    private Matcher matcher;
 
    private static final String IPADDRESS_PATTERN = 
		"^([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])$";
 
    public IPAddressValidator(){
	  pattern = Pattern.compile(IPADDRESS_PATTERN);
    }
 
   /**
    * Validate ip address with regular expression
    * @param ip ip address for validation
    * @return true valid ip address, false invalid ip address
    */
    public boolean validate(final String ip){		  
	  matcher = pattern.matcher(ip);
	  return matcher.matches();	    	    
    }
}

2. IP address that matches :

1. “1.1.1.1”, “255.255.255.255”,”192.168.1.1″ ,
2. “10.10.1.1”, “132.254.111.10”, “26.10.2.10”,
3. “127.0.0.1”

3. IP address that doesn’t match :

1. “10.10.10” – must have 4 “.”
2. “10.10” – must have 4 “.”
3. “10” – must have 4 “.”
4. “a.a.a.a” – only digit has allowed
5. “10.0.0.a” – only digit has allowed
6. “10.10.10.256” – digit must between [0-255]
7. “222.222.2.999” – digit must between [0-255]
8. “999.10.10.20” – digit must between [0-255]
9. “2222.22.22.22” – digit must between [0-255]
10. “22.2222.22.2” – digit must between [0-255]

4. Unit Test

IPAddressValidatorTest.java
package com.mkyong.regex;
 
import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * IPAddress validator Testing
 * @author mkyong
 *
 */
public class IPAddressValidatorTest {
 
	private IPAddressValidator ipAddressValidator;
 
	@BeforeClass
        public void initData(){
		ipAddressValidator = new IPAddressValidator();
        }
 
	@DataProvider
	public Object[][] ValidIPAddressProvider() {
		return new Object[][]{
		   new Object[] {"1.1.1.1"},new Object[] {"255.255.255.255"},
                   new Object[] {"192.168.1.1"},new Object[] {"10.10.1.1"},
                   new Object[] {"132.254.111.10"},new Object[] {"26.10.2.10"},
		   new Object[] {"127.0.0.1"}
		};
	}
 
	@DataProvider
	public Object[][] InvalidIPAddressProvider() {
		return new Object[][]{
		   new Object[] {"10.10.10"},new Object[] {"10.10"},
                   new Object[] {"10"},new Object[] {"a.a.a.a"},
                   new Object[] {"10.0.0.a"},new Object[] {"10.10.10.256"},
		   new Object[] {"222.222.2.999"},new Object[] {"999.10.10.20"},
                   new Object[] {"2222.22.22.22"},new Object[] {"22.2222.22.2"},
                   new Object[] {"10.10.10"},new Object[] {"10.10.10"},	
		};
	}
 
	@Test(dataProvider = "ValidIPAddressProvider")
	public void ValidIPAddressTest(String ip) {
		   boolean valid = ipAddressValidator.validate(ip);
		   System.out.println("IPAddress is valid : " + ip + " , " + valid);
		   Assert.assertEquals(true, valid);
	}
 
	@Test(dataProvider = "InvalidIPAddressProvider",
                 dependsOnMethods="ValidIPAddressTest")
	public void InValidIPAddressTest(String ip) {
		   boolean valid = ipAddressValidator.validate(ip);
		   System.out.println("IPAddress is valid : " + ip + " , " + valid);
		   Assert.assertEquals(false, valid); 
	}	
}

5. Unit Test – Result

IPAddress is valid : 1.1.1.1 , true
IPAddress is valid : 255.255.255.255 , true
IPAddress is valid : 192.168.1.1 , true
IPAddress is valid : 10.10.1.1 , true
IPAddress is valid : 132.254.111.10 , true
IPAddress is valid : 26.10.2.10 , true
IPAddress is valid : 127.0.0.1 , true
IPAddress is valid : 10.10.10 , false
IPAddress is valid : 10.10 , false
IPAddress is valid : 10 , false
IPAddress is valid : a.a.a.a , false
IPAddress is valid : 10.0.0.a , false
IPAddress is valid : 10.10.10.256 , false
IPAddress is valid : 222.222.2.999 , false
IPAddress is valid : 999.10.10.20 , false
IPAddress is valid : 2222.22.22.22 , false
IPAddress is valid : 22.2222.22.2 , false
PASSED: ValidIPAddressTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidIPAddressTest([Ljava.lang.String;@116471f)
 
===============================================
    com.mkyong.regex.IPAddressValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================
 
===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Reference

  1. http://en.wikipedia.org/wiki/IP_address
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Google()

  • http://www.texylvania.org/userinfo.php?uid=89325 fetishes

    I am really inspired together with your writing abilities as smartly as with the format for your blog.

    Is that this a paid topic or did you modify it yourself?
    Anyway keep up the nice high quality writing, it is uncommon to peer a nice
    weblog like this one these days..

  • http://[email protected] Arsalan Khan

    How to make it fail for 255.255.255.255?

  • http://binary.duapp.com/2012/11/653.html visit for names golden retriever content

    Excellent pieces. Keep posting such kind of information on your
    site. Im really impressed by your blog.
    Hi there, You have done a great job. I’ll certainly digg it and in my view suggest to my friends.

    I’m confident they’ll be benefited from this web site.

  • http://poduszkiciazowe.pl/ poduszkiciazowe.pl

    I got this web site from my buddy who shared with me concerning this website and now this
    time I am browsing this site and reading very informative content here.

  • http://technorati.com/people/PalmaLaffe/ king size memory foam mattress cover

    No matter if some one searches for his necessary thing,
    so he/she wishes to be available that inn detail, therefore that
    thing is maintained over here.

  • http://www.xboxmicrosoftpoints.org/xboxlive1monthgold.php microsoft points kopen

    Quality articles is the crucial to interest the visitors to go
    to see the website, that’s what this site is providing.

  • http://irrationalimports.com/ irrationalimports.com

    After I initially left a comment I appear to have clicked on the -Notify me when new comments are added-
    checkbox and now each time a comment is added I recieve four emails
    with the exact same comment. Perhaps there is
    a way you can remove me from that service? Many thanks!

  • http://eperfectionist.blogspot.com/2012/12/giveaway.html Ferdinand

    Excellent blog here! Also your site lots up fast! What host
    are you the usage of? Can I get your affiliate linnk on your host?
    I want my website loaded up as fast as yours lol

  • http://www.zoepa-photography.be/esion/index.php/guestbook/entry raspberry pi alternative

    I seldom leave a response, but i did a few searching and wound
    up here How to validate IP address with regular expression.
    And I do have a couple of questions for you if it’s allright. Could it be just me or does it give the impression like a few of these remarks come across as if they are written by brain dead folks? :-P And, if you are writing at other places, I would like to keep up with anything fresh you have to post. Could you make a list of the complete urls of all your shared sites like your twitter feed, Facebook page or linkedin profile?

  • Arpith

    Does not work for 10.106.2142 (2 digits and a 4-digit octet but it is still a valid IP; ping it if you will)

  • Abhideep

    Does not work for 10.0.0.8 …

  • https://sites.google.com/site/mydreamchurch/ Anil

    Thanks for posting this code – is it available for use freely? Appreciate your making it available.

  • https://sites.google.com/site/mydreamchurch/ Anil

    Thanks for posting this code – is it available for use freely?

  • http://regex-for.com David Scherfgen

    Nice article.
    The question arises whether you want to use a very simple regex that will just look for four 3-digit numbers separated by dots and then filter the candidates in your programming language, or whether you want to use the quite complex one that has the “< 256" constraint built into it.
    Would be interesting to see a performance comparison …

    PS:
    I also wrote an article about regex and IP addresses (IPv4 and IPv6).
    IPv6 is so much easier to match because it uses hex numbers! :-)
    http://regex-for.com/ip-addresses/

  • Pingback: How to execute shell command from Java()

  • http://nil nirmal

    Hi,
    This program says 10.1.0.0 is a valid ip but this is not valid i believe, please see below link

    http://www.comptechdoc.org/independent/networking/guide/netaddressing.html

    • http://www.fikrifadzil.com Fikri Fadzil

      10.1.0.0 is still a valid ip address.

      .0 is used for network address.
      .255 is used for broadcast address.

      between both, all the addresses are used for hosts. whether the ip is valid or not… those are valid ip. Based on the URL you quoted from, 10.1.0.0 is not a valid host address because it is a network address.

  • ozgun

    IPAddressValidator ipAddressValidator;
    ipAddressValidator = new IPAddressValidator();
    InetAddress address = null;

    boolean valid = ipAddressValidator.validate(“01.03.01.04″);
    System.out.println(“IPAddress is valid : ” + ” , ” + valid);

    try {
    address = InetAddress.getByName(“01.0.000.05″);
    } catch (UnknownHostException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

  • ozgun

    More easy way:
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    InetAddress address = null;
    try {
    address = InetAddress.getByName(“444.156.115.59″);
    } catch (UnknownHostException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    java.net.UnknownHostException: 444.156.115.59
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)

  • Szeak

    oh – \\. at the and sorry :)

  • Szeak

    Your pattern may like more pritty with this mode:

    ^([01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])){3}\\.$

    My pattern is :

    ^(?:\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])(?:\\.(?:\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}$
  • Pingback: Java Regular Expression Tutorial()

  • binhnhi

    Hello mkyoung,

    I think in this code
    @Test(dataProvider = “ValidIPAddressProvider”)
    public void ValidIPAddressTest(String IPAddress) {
    boolean valid = ipAddressValidator.validate(temp);
    System.out.println(“IPAddress is valid : ” + temp + ” , ” + valid);
    Assert.assertEquals(true, valid);
    }
    we should use this line “Assert.assertEquals(valid, true);” for correction with API doc
    and avoid wrong message in test report

    Thank you very much

  • Pingback: Regex help? - Java Forums()

  • http://iiita Vijay Bhaskar Semwal

    Regular expression for Floating Point Number

    The use of nearly duplicate expressions joined with the or operator “|” to permit the decimal point to lead or follow digits.

    {[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?}
    [-+]?([0-9]+\.?[0-9]* .. will lead e.g= -2.0129…
    [-+]?([0-9]+\.[0-9]+)([eE][-+]?[0-9]+) .. will lead e.g – 2.3+e123
    Vijay Bhaskar Semwal
    B.tech.+M.tech.
    IIIT Allahabad

  • Jaime

    127.000.000.001
    000.000.000.000

    Matches too, which would be the best way to modify regex to disallow it?

    • Akshat Kakkar

      but isn’t these valid IP Addresses!!!

  • Noor Ahmed

    what is the regular expression for IP address in flex? please help me

  • Pingback: 10 Java Regular Expression Examples You Should Know | Regular Expressions()

  • Cedric

    Keep in mind that each line represents a list of parameters to pass to your method, so it has to be a new Object[] in case your test method can accept more than one parameter.

    Anyway, I’m not sure I understand your worry, you are creating the same number of objects in either case, but in the code I gave you, you are letting the data provider do the loop instead of doing it in your test method, that’s all…

    • mkyong

      i’m honestly thanks your help. Your are enlighten me in some ways ;), and letting the data provider do the loop is more better.

  • mkyong

    Code changed to :

    @DataProvider
    public Object[][] ValidIPAddressProvider() {
    return new Object[][]{
    new Object[] {“1.1.1.1″},new Object[] {“255.255.255.255″},new Object[] {“192.168.1.1″},
    new Object[] {“10.10.1.1″},new Object[] {“132.254.111.10″},new Object[] {“26.10.2.10″},
    new Object[] {“127.0.0.1″}
    };
    }

    It’s look too many new objects around, is there a more elegant way to implement it?

  • Cedric

    You’re still passing an array of strings to each method call, here is the correct version:

    http://pastie.org/690351

    The difference is that you let the data provider do the loop instead of your test method…

    Hope this makes sense.

    • mkyong

      Got it, thanks for the guidance, i really appreciated it ;)

    • Amit

      Hi cedric.
      I have an issue with the range of IP address.
      If i enter the starting Ip and the Ending IP
      I should get the list all the Ips within that range.
      Can u pls guide me on this.

      For Example String start = “192.168.0.2”;
      String end = “195.160.0.254”;

      i have to get all the Ips with in this range.
      Pls help me out with this .

      • Amit

        public static void main(String[] args) {
        String start = “192.168.0.2”;
        String end = “195.160.0.254”;

        String[] startParts = start.split(“(?<=\\.)(?!.*\\.)");
        String[] endParts = end.split("(?<=\\.)(?!.*\\.)");

        int first = Integer.parseInt(startParts[1]);
        int last = Integer.parseInt(endParts[1]);

        for (int i = first; i <= last; i++) {
        System.out.println(startParts[0] + i);
        }

        }

        I have tried with this above example. but wont exceed 192 range.. i want a api where in any ranges given the list of all the Ips in that range shoild be displayed..

  • Cedric

    A quick remark: you are not using data providers to their fullest: your test method should accept a single string and your data provider should return arrays of single string objects:

    return new Object[][] {
    { new Object[] { “10.10.10” }}
    { new Object[] { “10.10” }}
    }

    and:

    @Test(dataProvider = “ValidIPAddressProvider”)
    public void ValidIPAddressTest(String IPAddress) {
    boolean valid = ipAddressValidator.validate(temp);
    System.out.println(“IPAddress is valid : ” + temp + ” , ” + valid);
    Assert.assertEquals(true, valid);
    }
    }

    • mkyong

      Cedric!? author of testNG!?, thanks for the remark, but i keep hit the argument type error, can you comment on it?

      With String as argument in test method
      @Test(dataProvider = “ValidIPAddressProvider”)
      public void ValidIPAddressTest(String IPAddress) {…}

      1) Return single array of string
      @DataProvider
      public Object[][] ValidIPAddressProvider() {
      return new Object[][]{
      {new String[] {“1.1.1.1″}}
      };
      }

      FAILED: ValidIPAddressTest(“[Ljava.lang.String;@1632c2d”)
      java.lang.IllegalArgumentException: argument type mismatch

      1) Return single array of object
      @DataProvider
      public Object[][] ValidIPAddressProvider() {
      return new Object[][]{
      {new Object[] {“1.1.1.1″}}
      };
      }
      FAILED: ValidIPAddressTest(“[Ljava.lang.Object;@1632c2d”)
      java.lang.IllegalArgumentException: argument type mismatch