3

I want to check if a string is an IPv4 or IPv6 address, but NOTHING else. Is there any way to accomplish this using standard java libs?

I know of:

  • InetAddress.getByName(str) - but it accepts hostnames
  • IPAddressUtil.isIPv4LiteralAddress(str) - but it is an internal class and will give compiler warnings

I know I could use regular expressions, but I prefer to use existing methods.

honeyp0t
  • 837
  • 8
  • 15
  • I think we can agree that there is no standard (as in, included by default) way of accomplishing this. What I ended up doing was to run the supposed IP address through a sloppy IPv4|6 regexp (to sort out anything that does not _look_ like a valid IP address) and then call InetAddress.getByName(str) on the address. – honeyp0t Feb 28 '12 at 07:40
  • could you post the working solution in java ? – deepakl.2000 May 30 '21 at 14:14

4 Answers4

3

You can use InetAddresses.forString(), from this library:

http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/net/InetAddresses.java

Paul
  • 31
  • 1
1

The way to do this in C is to use inet_pton(). You could port the code to Java. (Or use some really complicated regular expressions, because matching IPv6 addresses isn't simple.)

You could take a look at the regular expression in this question and change it so it doesn't match hostnames, if you're feeling brave. ;-)

Community
  • 1
  • 1
mpontillo
  • 13,559
  • 7
  • 62
  • 90
0

The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner. It has methods to do what you are describing.

Here is sample code that solves your problem.

Here is more sample code:

IPAddressString ipString = new IPAddressString("ipv4 or ipv6 address string goes here");
System.out.println("IPv4: " + ipString.isIpV4() + " IPv6: " + ipString.isIpV6()); 
Sean F
  • 4,344
  • 16
  • 30
-2

Simple rule of thumbs is if the address is x.x.x.x.x.x.x.x then its an IPV6 address...Try looking into the classes Inet4Address and Inet6Address as well.

Mikematic
  • 329
  • 3
  • 7