How can I determine the IP of my router/gateway in Java?

前端 未结 16 2194
无人及你
无人及你 2020-11-27 06:43

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 gat

16条回答
  •  迷失自我
    2020-11-27 07:14

    You can use netstat -rn command which is available on Windows, OSX, Linux, etc platform. Here is my code:

    private String getDefaultAddress() {
            String defaultAddress = "";
            try {
                Process result = Runtime.getRuntime().exec("netstat -rn");
    
                BufferedReader output = new BufferedReader(new InputStreamReader(
                        result.getInputStream()));
    
                String line = output.readLine();
                while (line != null) {
                    if (line.contains("0.0.0.0")) {
    
                        StringTokenizer stringTokenizer = new StringTokenizer(line);
                        stringTokenizer.nextElement(); // first element is 0.0.0.0
                        stringTokenizer.nextElement(); // second element is 0.0.0.0
                        defaultAddress = (String) stringTokenizer.nextElement();
                        break;
                    }
    
                    line = output.readLine();
    
                } // while
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return defaultAddress;
    
    } // getDefaultAddress
    

提交回复
热议问题