Get default gateway in java

后端 未结 5 1641
旧巷少年郎
旧巷少年郎 2020-12-19 05:30

I want to fetch default gateway for local machine using java. I know how to get it by executing dos or shell commands, but is there any another way to fetch? Also need to fe

5条回答
  •  我在风中等你
    2020-12-19 05:48


    In Windows with the help of ipconfig:

    import java.awt.Desktop;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URI;
    
    public final class Router {
    
        private static final String DEFAULT_GATEWAY = "Default Gateway";
    
        private Router() {
        }
    
        public static void main(String[] args) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Process process = Runtime.getRuntime().exec("ipconfig");
    
                    try (BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(process.getInputStream()))) {
    
                        String line;
                        while ((line = bufferedReader.readLine()) != null) {
                            if (line.trim().startsWith(DEFAULT_GATEWAY)) {
                                String ipAddress = line.substring(line.indexOf(":") + 1).trim(),
                                        routerURL = String.format("http://%s", ipAddress);
    
                                // opening router setup in browser
                                Desktop.getDesktop().browse(new URI(routerURL));
                            }
    
                            System.out.println(line);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    Here I'm getting the default gateway IP address of my router, and opening it in a browser to see my router's setup page.

提交回复
热议问题