Reputation: 927
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
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
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
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