honeyp0t
honeyp0t

Reputation: 927

Match IPv4 and IPv6 addresses but NOT hostname?

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:

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

Upvotes: 3

Views: 1217

Answers (4)

Sean F
Sean F

Reputation: 4615

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

Upvotes: 0

mpontillo
mpontillo

Reputation: 13967

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

Upvotes: 1

Paul
Paul

Reputation: 31

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

Upvotes: 3

Mikematic
Mikematic

Reputation: 358

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.

Upvotes: -2

Related Questions