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

前端 未结 16 2235
无人及你
无人及你 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:06

    Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:

    import java.io.*;
    import java.util.*;
    
    public class ExecTest {
        public static void main(String[] args) throws IOException {
            Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
    
            BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
            String thisLine = output.readLine();
            StringTokenizer st = new StringTokenizer(thisLine);
            st.nextToken();
            String gateway = st.nextToken();
            System.out.printf("The gateway is %s\n", gateway);
        }
    }
    

    This presumes that the gateway is the second token and not the third. If it is, you need to add an extra st.nextToken(); to advance the tokenizer one more spot.

提交回复
热议问题