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

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

    On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using

    netstat -rn
    

    in place of a traceroute command.

    Your gateway's IP address will appear in the second field of the line that starts either default or 0.0.0.0.

    This gets around a number of problems with trying to use traceroute:

    1. on Windows traceroute is actually tracert.exe, so there's no need for O/S dependencies in the code
    2. it's a quick command to run - it gets information from the O/S, not from the network
    3. traceroute is sometimes blocked by the network

    The only downside is that it will be necessary to keep reading lines from the netstat output until the right line is found, since there'll be more than one line of output.

    EDIT: The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the third field of the line that starts with '0.0.0.0' (tested on Windows 7)

    Windows:

    Network Destination Netmask Gateway Interface Metric

    0.0.0.0 0.0.0.0 192.168.2.254 192.168.2.46 10

    Mac:

    Destination Gateway Flags Refs Use Netif Expire

    default 192.168.2.254 UGSc 104 4 en1

提交回复
热议问题