netif.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. addrs, err := net.InterfaceAddrs()
  37. if err != nil {
  38. return
  39. }
  40. for _, inter := range addrs {
  41. if len(inter.String()) == 0 {
  42. continue
  43. }
  44. ip := strings.Split(inter.String(), "/")[0]
  45. if isInternalIP(ip) {
  46. InternalIP = ip
  47. } else {
  48. ExternalIP = ip
  49. }
  50. }
  51. return
  52. }
  53. // fix host ip with "internal:port" or "external:port" format
  54. func fixHostIp(addr string) (string, error) {
  55. if strings.Contains(addr, confInternalIP) {
  56. if InternalIP != "" {
  57. addr = strings.Replace(addr, confInternalIP, InternalIP, -1)
  58. } else {
  59. return addr, errors.New("server has no internal ip")
  60. }
  61. } else if strings.Contains(addr, confExternalIP) {
  62. if ExternalIP != "" {
  63. addr = strings.Replace(addr, confExternalIP, ExternalIP, -1)
  64. } else {
  65. return addr, errors.New("server has no external ip")
  66. }
  67. }
  68. return addr, nil
  69. }