Get default gateway in java

后端 未结 5 1639
旧巷少年郎
旧巷少年郎 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:50

    My way is:

    try(DatagramSocket s=new DatagramSocket())
    {
        s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0);
        return NetworkInterface.getByInetAddress(s.getLocalAddress()).getHardwareAddress();
    }
    

    Because of using datagram (UDP), it isn't connecting anywhere, so port number may be meaningless and remote address (1.1.1.1) needn't be reachable, just routable.

提交回复
热议问题