Get default gateway in java

Nirmal- thInk beYond picture Nirmal- thInk beYond · May 10, 2011 · Viewed 15.5k times · Source

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 fetch primary and secondary dns ip.

Answer

motas picture motas · Nov 19, 2014

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.