gateway_windows.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package gateway
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net"
  6. "os/exec"
  7. )
  8. func DiscoverGateway() (ip net.IP, err error) {
  9. routeCmd := exec.Command("route", "print", "0.0.0.0")
  10. stdOut, err := routeCmd.StdoutPipe()
  11. if err != nil {
  12. return
  13. }
  14. if err = routeCmd.Start(); err != nil {
  15. return
  16. }
  17. output, err := ioutil.ReadAll(stdOut)
  18. if err != nil {
  19. return
  20. }
  21. // Windows route output format is always like this:
  22. // ===========================================================================
  23. // Active Routes:
  24. // Network Destination Netmask Gateway Interface Metric
  25. // 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.100 20
  26. // ===========================================================================
  27. // I'm trying to pick the active route,
  28. // then jump 2 lines and pick the third IP
  29. // Not using regex because output is quite standard from Windows XP to 8 (NEEDS TESTING)
  30. outputLines := bytes.Split(output, []byte("\n"))
  31. for idx, line := range outputLines {
  32. if bytes.Contains(line, []byte("Active Routes:")) {
  33. ipFields := bytes.Fields(outputLines[idx+2])
  34. ip = net.ParseIP(string(ipFields[2]))
  35. break
  36. }
  37. }
  38. err = routeCmd.Wait()
  39. return
  40. }