tags:

views:

439

answers:

6

So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?

Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.

+11  A: 

You can use a regular expression with this pattern:

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

That will tell you if it's an IPv4 address.

Sam
I think just testing for the digit pattern is more than enough, if you need real range validation, regex is really not the best way to do it.
DevelopingChris
+2  A: 

You can see if the string matches the number.number.number.number format, for example: \b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b will match anything from 0 - 999.

Anything else you can have it default to hostname.

zxcv
999.999.999.999 is not a valid ip format. your regex needs to be more specific
Vagnerr
don't think its a valid host name either
DevelopingChris
+2  A: 

Do we get to make the assumption that it is one or the other, and not something completely different? If so, I'd probably use a regex to see if it matched the "dotted quad" format.

Joel Coehoorn
A: 

Couldn't you just to a regexp match on it?

davetron5000
+1  A: 
URI validator = new URI(yourString);

That code will validate the IP address or Hostname. (It throws a malformed URI Exception if the string is invalid)

If you are trying to distinguish the two..then I miss read your question.

jjnguy
A: 

You can use a security manager with the InetAddress.getByName(addr) call.

If the addr is not a dotted quad, getByName will attempt to perform a connect to do the name lookup, which the security manager can capture as a checkConnect(addr, -1) call, resulting in a thrown SecurityException that you can catch.

You can use System.setSecurityManager() if you're running fully privileged to insert your custom security manager before the getByName call is made.

davenpcj