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

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

    I'm not sure if it works on every system but at least here I found this:

    import java.net.InetAddress;
    import java.net.UnknownHostException;
    public class Main
    {
        public static void main(String[] args)
        {
            try
            {
                //Variables to find out the Default Gateway IP(s)
                String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();
                String hostName = InetAddress.getLocalHost().getHostName();
    
                //"subtract" the hostName from the canonicalHostName, +1 due to the "." in there
                String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);
    
                //Info printouts
                System.out.println("Info:\nCanonical Host Name: " + canonicalHostName + "\nHost Name: " + hostName + "\nDefault Gateway Leftover: " + defaultGatewayLeftover + "\n");
                System.out.println("Default Gateway Addresses:\n" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));
            } catch (UnknownHostException e)
            {
                e.printStackTrace();
            }
        }
        //simple combined string out of the address array
        private static String printAddresses(InetAddress[] allByName)
        {
            if (allByName.length == 0)
            {
                return "";
            } else
            {
                String str = "";
                int i = 0;
                while (i < allByName.length - 1)
                {
                    str += allByName[i] + "\n";
                    i++;
                }
                return str + allByName[i];
            }
        }
    }
    

    For me this produces:

    Info:
    Canonical Host Name: PCK4D-PC.speedport.ip
    Host Name: PCK4D-PC
    Default Gateway Leftover: speedport.ip
    
    Default Gateway Addresses:
    speedport.ip/192.168.2.1
    speedport.ip/fe80:0:0:0:0:0:0:1%12
    

    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.

提交回复
热议问题