<p>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?</p>

<p>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.</p>

[{'answer_id': 66944, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 5, 'selected': True, 'text': "<p>You can use a regular expression with this pattern:</p>\n\n<pre><code>\\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\n</code></pre>\n\n<p>That will tell you if it's an IPv4 address.</p>\n"}, {'answer_id': 66947, 'author': 'zxcv', 'author_id': 9628, 'author_profile': 'https://Stackoverflow.com/users/9628', 'pm_score': 2, 'selected': False, 'text': '<p>You can see if the string matches the number.number.number.number format, for example:</p>\n\n<pre><code>\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\n</code></pre>\n\n<p>will match anything from <code>0 - 999</code>.</p>\n\n<p>Anything else you can have it default to hostname.</p>\n'}, {'answer_id': 66948, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 2, 'selected': False, 'text': '<p>Do we get to make the assumption that it <em>is</em> 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.</p>\n'}, {'answer_id': 66951, 'author': 'davetron5000', 'author_id': 3029, 'author_profile': 'https://Stackoverflow.com/users/3029', 'pm_score': 0, 'selected': False, 'text': "<p>Couldn't you just to a regexp match on it?</p>\n"}, {'answer_id': 66989, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 1, 'selected': False, 'text': '<pre><code>URI validator = new URI(yourString);\n</code></pre>\n\n<p>That code will validate the IP address or Hostname. (It throws a malformed URI Exception if the string is invalid)</p>\n\n<p>If you are trying to distinguish the two..then I miss read your question.</p>\n'}, {'answer_id': 67156, 'author': 'davenpcj', 'author_id': 4777, 'author_profile': 'https://Stackoverflow.com/users/4777', 'pm_score': 1, 'selected': False, 'text': "<p>You can use a security manager with the <code>InetAddress.getByName(addr)</code> call. </p>\n\n<p>If the addr is not a dotted quad, <code>getByName</code> will attempt to perform a connect to do the name lookup, which the security manager can capture as a <code>checkConnect(addr, -1)</code> call, resulting in a thrown SecurityException that you can catch.</p>\n\n<p>You can use <code>System.setSecurityManager()</code> if you're running fully privileged to insert your custom security manager before the <code>getByName</code> call is made.</p>\n"}, {'answer_id': 40135432, 'author': 'Sean F', 'author_id': 6801443, 'author_profile': 'https://Stackoverflow.com/users/6801443', 'pm_score': 1, 'selected': False, 'text': '<p>It is not as simple as it may appear, there are some ambiguities around characters like hyphens, underscore, and square brackets \'-\', \'_\', \'[]\'.</p>\n\n<p>The Java SDK is has some limitations in this area.  When using InetAddress.getByName it will go out onto the network to do a DNS name resolution and resolve the address, which is expensive and unnecessary if all you want is to detect host vs address.  Also, if an address is written in a slightly different but valid format (common in IPv6) doing a string comparison on the results of InetAddress.getByName will not work.</p>\n\n<p><a href="https://seancfoley.github.io/IPAddress/" rel="nofollow">The IPAddress Java library</a> will do it.  The javadoc is available at the link.  Disclaimer: I am the project manager.</p>\n\n<pre><code>static void check(HostName host) {\n    try {\n        host.validate();\n        if(host.isAddress()) {\n            System.out.println("address: " + host.asAddress());\n        } else {\n            System.out.println("host name: " + host);\n        }\n    } catch(HostNameException e) {\n        System.out.println(e.getMessage());\n    }\n}\n\npublic static void main(String[] args) {\n    HostName host = new HostName("1.2.3.4");\n    check(host);\n    host = new HostName("1.2.a.4");\n    check(host);\n    host = new HostName("::1");\n    check(host);\n    host = new HostName("[::1]");\n    check(host);\n    host = new HostName("1.2.?.4");\n    check(host);  \n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>address: 1.2.3.4\nhost name: 1.2.a.4\naddress: ::1\naddress: ::1\n1.2.?.4 Host error: invalid character at index 4\n</code></pre>\n'}, {'answer_id': 57612280, 'author': 'Denis Kalinin', 'author_id': 4919616, 'author_profile': 'https://Stackoverflow.com/users/4919616', 'pm_score': 0, 'selected': False, 'text': '<p>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html#getAllByName-java.lang.String-" rel="nofollow noreferrer">InetAddress#getAllByName(String hostOrIp)</a> - if <code>hostOrIp</code> is an IP-address the result is an array with single InetAddress and it\'s <code>.getHostAddress()</code> returns the same string as <code>hostOrIp</code>.</p>\n\n<pre class="lang-java prettyprint-override"><code>import java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Arrays;\n\npublic class IPvsHostTest {\n    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(IPvsHostTest.class);\n\n    @org.junit.Test\n    public void checkHostValidity() {\n        Arrays.asList("10.10.10.10", "google.com").forEach( hostname -&gt; isHost(hostname));\n    }\n    private void isHost(String ip){\n        try {\n            InetAddress[] ips = InetAddress.getAllByName(ip);\n            LOG.info("IP-addresses for {}", ip);\n            Arrays.asList(ips).forEach( ia -&gt; {\n                LOG.info(ia.getHostAddress());\n            });\n        } catch (UnknownHostException e) {\n            LOG.error("Invalid hostname", e);\n        }\n    }\n}\n\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>IP-addresses for 10.10.10.10\n10.10.10.10\nIP-addresses for google.com\n64.233.164.100\n64.233.164.138\n64.233.164.139\n64.233.164.113\n64.233.164.102\n64.233.164.101\n</code></pre>\n'}, {'answer_id': 63747626, 'author': 'BillS', 'author_id': 5415282, 'author_profile': 'https://Stackoverflow.com/users/5415282', 'pm_score': 0, 'selected': False, 'text': '<p>This code still performs the DNS lookup if a host name is specified, but at least it skips the reverse lookup that may be performed with other approaches:</p>\n<pre><code>   ...\n   isDottedQuad(&quot;1.2.3.4&quot;);\n   isDottedQuad(&quot;google.com&quot;);\n   ...\n\nboolean isDottedQuad(String hostOrIP) throws UnknownHostException {\n   InetAddress inet = InetAddress.getByName(hostOrIP);\n   boolean b = inet.toString().startsWith(&quot;/&quot;);\n   System.out.println(&quot;Is &quot; + hostOrIP + &quot; dotted quad? &quot; + b + &quot; (&quot; + inet.toString() + &quot;)&quot;);\n   return b;\n}\n</code></pre>\n<p>It generates this output:</p>\n<pre><code>Is 1.2.3.4 dotted quad? true (/1.2.3.4)\nIs google.com dotted quad? false (google.com/172.217.12.238)\n</code></pre>\n<p>Do you think we can expect the toString() behavior to change anytime soon?</p>\n'}]
['https://Stackoverflow.com/questions/66923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10059/']