<p>How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?</p>

<p>This is somewhat easy in .NET if you know your way around. But how do you do it in Java?</p>

[{'answer_id': 11943, 'author': 'Brian', 'author_id': 725, 'author_profile': 'https://Stackoverflow.com/users/725', 'pm_score': 1, 'selected': False, 'text': "<p>That is not as easy as it sounds.  Java is platform independent, so I am not sure how to do it in Java.  I am <em>guessing</em> that .NET contacts some web site which reports it back.  There are a couple ways to go.  First, a deeper look into the ICMP protocol may give you the information you need.  You can also trace the IP you go through (your route).  When you encounter an IP that is not in the following ranges:</p>\n\n<ul>\n<li>10.0.0.0 – 10.255.255.255</li>\n<li>172.16.0.0 – 172.31.255.255</li>\n<li>192.168.0.0 – 192.168.255.255</li>\n</ul>\n\n<p>it is the IP one hop away from yours, and probably shares a few octets of information with your IP.</p>\n\n<p>Best of luck.  I'll be curious to hear a definitive answer to this question.</p>\n"}, {'answer_id': 11960, 'author': 'Nick Brosnahan', 'author_id': 528, 'author_profile': 'https://Stackoverflow.com/users/528', 'pm_score': 1, 'selected': False, 'text': "<p>Try shelling out to traceroute if you have it.</p>\n\n<p>'traceroute -m 1 www.amazon.com' will emit something like this:</p>\n\n<pre><code>traceroute to www.amazon.com (72.21.203.1), 1 hops max, 40 byte packets\n 1  10.0.1.1 (10.0.1.1)  0.694 ms  0.445 ms  0.398 ms\n</code></pre>\n\n<p>Parse the second line.  Yes, it's ugly, but it'll get you going until someone posts something nicer.</p>\n"}, {'answer_id': 12013, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 2, 'selected': False, 'text': '<p>You may be better off using something like checkmyip.org, which will determine your public IP address - not necessarily your first hop router: at Uni I have a "real" IP address, whereas at home it is my local router\'s public IP address.</p>\n\n<p>You can parse the page that returns, or find another site that allows you to just get the IP address back as the only string.</p>\n\n<p>(I\'m meaning load this URL in Java/whatever, and then get the info you need).</p>\n\n<p>This should be totally platform independent.</p>\n'}, {'answer_id': 12027, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 1, 'selected': False, 'text': '<p>Matthew: Yes, that is what I meant by "I can get my internet IP using a service on a website." Sorry about being glib.</p>\n\n<p>Brian/Nick: Traceroute would be fine except for the fact that lots of these routers have ICMP disabled and thus it always stalls.</p>\n\n<p>I think a combination of traceroute and uPnP will work out. That is what I was planning on doing, I as just hoping I was missing something obvious.</p>\n\n<p>Thank you everyone for your comments, so it sounds like I\'m not missing anything obvious. I have begun implementing some bits of uPnP in order to discover the gateway.</p>\n'}, {'answer_id': 12030, 'author': 'Chris Bunch', 'author_id': 422, 'author_profile': 'https://Stackoverflow.com/users/422', 'pm_score': 5, 'selected': True, 'text': '<p>Java doesn\'t make this as pleasant as other languages, unfortunately. Here\'s what I did:</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\npublic class ExecTest {\n    public static void main(String[] args) throws IOException {\n        Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");\n\n        BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n        String thisLine = output.readLine();\n        StringTokenizer st = new StringTokenizer(thisLine);\n        st.nextToken();\n        String gateway = st.nextToken();\n        System.out.printf("The gateway is %s\\n", gateway);\n    }\n}\n</code></pre>\n\n<p>This presumes that the gateway is the second token and not the third. If it is, you need to add an extra <code>st.nextToken();</code> to advance the tokenizer one more spot.</p>\n'}, {'answer_id': 46957, 'author': 'Andreas Kraft', 'author_id': 4799, 'author_profile': 'https://Stackoverflow.com/users/4799', 'pm_score': 2, 'selected': False, 'text': '<p>Regarding UPnP: be aware that not all routers support UPnP. And if they do it could be switched off (for security reasons). So your solution might not always work.</p>\n\n<p>You should also have a look at NatPMP.</p>\n\n<p>A simple library for UPnP can be found  at <a href="http://miniupnp.free.fr/" rel="nofollow noreferrer">http://miniupnp.free.fr/</a>, though it\'s in C...</p>\n'}, {'answer_id': 61288, 'author': 'tardate', 'author_id': 6329, 'author_profile': 'https://Stackoverflow.com/users/6329', 'pm_score': 2, 'selected': False, 'text': '<p>To overcome the issues mentioned with traceroute (ICMP-based, wide area hit) you could consider:</p>\n\n<ol>\n<li>traceroute to your public IP (avoids wide-area hit, but still ICMP)</li>\n<li>Use a non-ICMP utility like ifconfig/ipconfig (portability issues with this though).</li>\n<li>What seems the best and most portable solution for now is to shell &amp; parse netstat (see the code example <a href="http://forums.sun.com/thread.jspa?threadID=5289135" rel="nofollow noreferrer">here</a>) </li>\n</ol>\n'}, {'answer_id': 61308, 'author': 'bruceatk', 'author_id': 791, 'author_profile': 'https://Stackoverflow.com/users/791', 'pm_score': 3, 'selected': False, 'text': '<p>On windows parsing the output of IPConfig will get you the default gateway, without waiting for a trace.</p>\n'}, {'answer_id': 247216, 'author': 'Alnitak', 'author_id': 6782, 'author_profile': 'https://Stackoverflow.com/users/6782', 'pm_score': 5, 'selected': False, 'text': "<p>On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using </p>\n\n<pre><code>netstat -rn\n</code></pre>\n\n<p>in place of a <code>traceroute</code> command.</p>\n\n<p>Your gateway's IP address will appear in the second field of the line that starts either <code>default</code> or <code>0.0.0.0</code>.</p>\n\n<p>This gets around a number of problems with trying to use <code>traceroute</code>:</p>\n\n<ol>\n<li>on Windows <code>traceroute</code> is actually <code>tracert.exe</code>, so there's no need for O/S dependencies in the code</li>\n<li>it's a quick command to run - it gets information from the O/S, not from the network</li>\n<li><code>traceroute</code> is sometimes blocked by the network</li>\n</ol>\n\n<p>The only downside is that it will be necessary to keep reading lines from the <code>netstat</code> output until the right line is found, since there'll be more than one line of output.</p>\n\n<p><strong>EDIT:</strong> The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the <strong>third field</strong> of the line that starts with '0.0.0.0' (tested on Windows 7)</p>\n\n<p>Windows:</p>\n\n<blockquote>\n  <blockquote>\n    <p>Network Destination        Netmask          Gateway       Interface  Metric</p>\n    \n    <p>0.0.0.0              0.0.0.0    <strong>192.168.2.254</strong>     192.168.2.46     10</p>\n  </blockquote>\n</blockquote>\n\n<p>Mac:</p>\n\n<blockquote>\n  <blockquote>\n    <p>Destination        Gateway            Flags        Refs      Use   Netif Expire</p>\n    \n    <p>default            <strong>192.168.2.254</strong>      UGSc          104        4     en1</p>\n  </blockquote>\n</blockquote>\n"}, {'answer_id': 248179, 'author': 'Hamza Yerlikaya', 'author_id': 29742, 'author_profile': 'https://Stackoverflow.com/users/29742', 'pm_score': 2, 'selected': False, 'text': '<pre class="lang-java prettyprint-override"><code>    try{\n        String gateway;\n        Process result = Runtime.getRuntime().exec("netstat -rn");\n\n        BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n\n        String line = output.readLine();\n        while(line != null){\n            if ( line.trim().startsWith("default") == true || line.trim().startsWith("0.0.0.0") == true )\n                break;      \n            line = output.readLine();\n        }\n        if(line==null) //gateway not found;\n            return;\n\n        StringTokenizer st = new StringTokenizer( line );\n        st.nextToken();\n        st.nextToken();\n        gateway = st.nextToken();\n        System.out.println("gateway is: "+gateway);\n\n\n    } catch( Exception e ) { \n        System.out.println( e.toString() );\n        gateway = new String();\n        adapter = new String();\n    }\n</code></pre>\n'}, {'answer_id': 274999, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You can query the URL "<a href="http://whatismyip.com/automation/n09230945.asp" rel="nofollow noreferrer">http://whatismyip.com/automation/n09230945.asp</a>".\nFor example:</p>\n\n<pre><code>    BufferedReader buffer = null;\n    try {\n        URL url = new URL("http://whatismyip.com/automation/n09230945.asp");\n        InputStreamReader in = new InputStreamReader(url.openStream());\n        buffer = new BufferedReader(in);\n\n        String line = buffer.readLine();\n        System.out.println(line);\n    } catch (IOException e) {\n        e.printStackTrace();\n    } finally {\n        try {\n            if (buffer != null) {\n                buffer.close();\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n</code></pre>\n'}, {'answer_id': 781223, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>output of netstat -rn is locale specific.\non my system (locale=de) the output looks like:\n...\nStandardgateway:         10.22.0.1</p>\n\n<p>so there is no line starting with 'default'.</p>\n\n<p>so using netstat might be no good idea.</p>\n"}, {'answer_id': 9005568, 'author': 'Loki Nightray', 'author_id': 1169530, 'author_profile': 'https://Stackoverflow.com/users/1169530', 'pm_score': 2, 'selected': False, 'text': '<p>This Version connects to www.whatismyip.com, reads the content of the site and searches via regular expressions the ip adress and prints it to the cmd. Its a little improvement of MosheElishas Code</p>\n\n<pre><code>import java.io.BufferedReader;  \nimport java.io.IOException;  \nimport java.io.InputStreamReader; \nimport java.net.URL;  \nimport java.util.regex.Matcher;  \nimport java.util.regex.Pattern;  \n\npublic class Main {\n\n    public static void main(String[] args) {\n        BufferedReader buffer = null;\n        try {\n            URL url = new URL(\n                    "http://www.whatismyip.com/tools/ip-address-lookup.asp");\n            InputStreamReader in = new InputStreamReader(url.openStream());\n            buffer = new BufferedReader(in);\n            String line = buffer.readLine();\n            Pattern pattern = Pattern\n                    .compile("(.*)value=\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\"(.*)");\n            Matcher matcher;\n            while (line != null) {\n                matcher = pattern.matcher(line);\n                if (matcher.matches()) {\n                    line = matcher.group(2) + "." + matcher.group(3) + "."\n                            + matcher.group(4) + "." + matcher.group(5);\n                    System.out.println(line);\n                }\n                line = buffer.readLine();\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n\n        } finally {\n            try {\n                if (buffer != null) {\n                    buffer.close();\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}\n\nimport java.io.BufferedReader;  \nimport java.io.IOException;  \nimport java.io.InputStreamReader; \nimport java.net.URL;  \nimport java.util.regex.Matcher;  \nimport java.util.regex.Pattern;  \n\npublic class Main {\n\n    public static void main(String[] args) {\n        BufferedReader buffer = null;\n        try {\n            URL url = new URL(\n                    "http://www.whatismyip.com/tools/ip-address-lookup.asp");\n            InputStreamReader in = new InputStreamReader(url.openStream());\n            buffer = new BufferedReader(in);\n            String line = buffer.readLine();\n            Pattern pattern = Pattern\n                    .compile("(.*)value=\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\"(.*)");\n            Matcher matcher;\n            while (line != null) {\n                matcher = pattern.matcher(line);\n                if (matcher.matches()) {\n                    line = matcher.group(2) + "." + matcher.group(3) + "."\n                            + matcher.group(4) + "." + matcher.group(5);\n                    System.out.println(line);\n                }\n                line = buffer.readLine();\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n\n        } finally {\n            try {\n                if (buffer != null) {\n                    buffer.close();\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 20806279, 'author': 'ZZ 5', 'author_id': 1646298, 'author_profile': 'https://Stackoverflow.com/users/1646298', 'pm_score': 1, 'selected': False, 'text': '<p>In windows you can just use the following command:</p>\n\n<pre><code>ipconfig | findstr /i "Gateway"\n</code></pre>\n\n<p>Which will give you output like:</p>\n\n<pre><code>Default Gateway . . . . . . . . . : 192.168.2.1\nDefault Gateway . . . . . . . . . : ::\n</code></pre>\n\n<p>However I can\'t run this command with Java, gonna post when I figure this out.</p>\n'}, {'answer_id': 36679773, 'author': 'chandan', 'author_id': 6216657, 'author_profile': 'https://Stackoverflow.com/users/6216657', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <code>netstat -rn</code> command which is available on Windows, OSX, Linux, etc platform. Here is my code:</p>\n\n<pre><code>private String getDefaultAddress() {\n        String defaultAddress = "";\n        try {\n            Process result = Runtime.getRuntime().exec("netstat -rn");\n\n            BufferedReader output = new BufferedReader(new InputStreamReader(\n                    result.getInputStream()));\n\n            String line = output.readLine();\n            while (line != null) {\n                if (line.contains("0.0.0.0")) {\n\n                    StringTokenizer stringTokenizer = new StringTokenizer(line);\n                    stringTokenizer.nextElement(); // first element is 0.0.0.0\n                    stringTokenizer.nextElement(); // second element is 0.0.0.0\n                    defaultAddress = (String) stringTokenizer.nextElement();\n                    break;\n                }\n\n                line = output.readLine();\n\n            } // while\n        } catch (IOException e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n\n        return defaultAddress;\n\n} // getDefaultAddress\n</code></pre>\n'}, {'answer_id': 54699876, 'author': 'PCK4D', 'author_id': 5750738, 'author_profile': 'https://Stackoverflow.com/users/5750738', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure if it works on every system but at least here I found this:</p>\n\n<pre><code>import java.net.InetAddress;\nimport java.net.UnknownHostException;\npublic class Main\n{\n    public static void main(String[] args)\n    {\n        try\n        {\n            //Variables to find out the Default Gateway IP(s)\n            String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();\n            String hostName = InetAddress.getLocalHost().getHostName();\n\n            //"subtract" the hostName from the canonicalHostName, +1 due to the "." in there\n            String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);\n\n            //Info printouts\n            System.out.println("Info:\\nCanonical Host Name: " + canonicalHostName + "\\nHost Name: " + hostName + "\\nDefault Gateway Leftover: " + defaultGatewayLeftover + "\\n");\n            System.out.println("Default Gateway Addresses:\\n" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));\n        } catch (UnknownHostException e)\n        {\n            e.printStackTrace();\n        }\n    }\n    //simple combined string out of the address array\n    private static String printAddresses(InetAddress[] allByName)\n    {\n        if (allByName.length == 0)\n        {\n            return "";\n        } else\n        {\n            String str = "";\n            int i = 0;\n            while (i &lt; allByName.length - 1)\n            {\n                str += allByName[i] + "\\n";\n                i++;\n            }\n            return str + allByName[i];\n        }\n    }\n}\n</code></pre>\n\n<p>For me this produces:</p>\n\n<pre><code>Info:\nCanonical Host Name: PCK4D-PC.speedport.ip\nHost Name: PCK4D-PC\nDefault Gateway Leftover: speedport.ip\n\nDefault Gateway Addresses:\nspeedport.ip/192.168.2.1\nspeedport.ip/fe80:0:0:0:0:0:0:1%12\n</code></pre>\n\n<p>I\'d require more tests on other Systems/Configurations/PC-Gateway-Setups to confirm if it works everywhere. Kind of doubt it but this was the first I found.</p>\n'}]
['https://Stackoverflow.com/questions/11930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338/']