Here you can find the source of getHostGateway()
public static InetAddress getHostGateway()
//package com.java2s; //License from project: Apache License import java.io.*; import java.net.*; import java.util.*; public class Main { public static InetAddress getHostGateway() { @SuppressWarnings("unused") String _gateway = null, _ip = null; if (System.getProperty("os.name").startsWith("Windows")) { return parseWindows(); }/*from w w w . jav a2s .c o m*/ try { BufferedReader reader = new BufferedReader(new FileReader("/proc/net/route")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); String[] tokens = line.split(" "); if (tokens.length > 1 && tokens[1].equals("00000000")) { String gateway = tokens[2]; //0102A8C0 if (gateway.length() == 8) { String[] s4 = new String[4]; s4[3] = String.valueOf(Integer.parseInt(gateway.substring(0, 2), 16)); s4[2] = String.valueOf(Integer.parseInt(gateway.substring(2, 4), 16)); s4[1] = String.valueOf(Integer.parseInt(gateway.substring(4, 6), 16)); s4[0] = String.valueOf(Integer.parseInt(gateway.substring(6, 8), 16)); _gateway = s4[0] + "." + s4[1] + "." + s4[2] + "." + s4[3]; } String iface = tokens[0]; NetworkInterface nif = NetworkInterface.getByName(iface); Enumeration<InetAddress> addrs = nif.getInetAddresses(); while (addrs.hasMoreElements()) { Object obj = addrs.nextElement(); if (obj instanceof Inet4Address) { _ip = obj.toString(); if (_ip.startsWith("/")) _ip = _ip.substring(1); } } } } reader.close(); return InetAddress.getByName(_ip); } catch (Exception ex) { } return null; } private static InetAddress parseWindows() { try { @SuppressWarnings("unused") String _gateway = null, _ip = null; Process pro = Runtime.getRuntime().exec("route print"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pro.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); String[] tokens = line.split(" "); List<String> args = new ArrayList<>(); for (String l : tokens) { if (!(l.equals("") || l.equalsIgnoreCase(" ") || l.startsWith(" "))) { args.add(l); } } tokens = args.toArray(new String[args.size()]); if (tokens.length == 5 && tokens[0].equals("0.0.0.0")) { _gateway = tokens[2]; _ip = tokens[3]; return InetAddress.getByName(tokens[2]); } } } catch (IOException ex) { } return null; } }