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:
- on Windows
traceroute is actually tracert.exe, so there's no need for O/S dependencies in the code
- it's a quick command to run - it gets information from the O/S, not from the network
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.