netif.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // netif implements helper functions to read network interfaces.
  2. // warning: ONLY suport standard Linux interface config.
  3. package server
  4. import (
  5. "errors"
  6. "net"
  7. "strings"
  8. )
  9. var (
  10. InternalIP string
  11. ExternalIP string
  12. )
  13. const (
  14. confInternalIP = "internal"
  15. confExternalIP = "external"
  16. )
  17. //to see if an IP is internal ip
  18. func isInternalIP(ip string) bool {
  19. if ip == "127.0.0.1" {
  20. return true
  21. }
  22. ipSplit := strings.Split(ip, ".")
  23. if ipSplit[0] == "10" {
  24. return true
  25. }
  26. if ipSplit[0] == "172" && ipSplit[1] >= "16" && ipSplit[1] <= "31" {
  27. return true
  28. }
  29. if ipSplit[0] == "192" && ipSplit[1] == "168" {
  30. return true
  31. }
  32. return false
  33. }
  34. //read server IP
  35. func readNetInterfaces() {
  36. interfaces, err := net.Interfaces()
  37. if err != nil {
  38. return
  39. }
  40. for _, inter := range interfaces {
  41. addr, err := inter.Addrs()
  42. if err != nil {
  43. continue
  44. }
  45. if !strings.Contains(inter.Name, "eth") {
  46. continue
  47. }
  48. if len(addr) == 0 {
  49. continue
  50. }
  51. ip := strings.Split(addr[0].String(), "/")[0]
  52. if isInternalIP(ip) {
  53. InternalIP = ip
  54. } else {
  55. ExternalIP = ip
  56. }
  57. }
  58. return
  59. }
  60. // fix host ip with "internal:port" or "external:port" format
  61. func fixHostIp(addr string) (string, error) {
  62. if strings.Contains(addr, confInternalIP) {
  63. if InternalIP != "" {
  64. addr = strings.Replace(addr, confInternalIP, InternalIP, -1)
  65. } else {
  66. return addr, errors.New("server has no internal ip")
  67. }
  68. } else if strings.Contains(addr, confExternalIP) {
  69. if ExternalIP != "" {
  70. addr = strings.Replace(addr, confExternalIP, ExternalIP, -1)
  71. } else {
  72. return addr, errors.New("server has no external ip")
  73. }
  74. }
  75. return addr, nil
  76. }