IP.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package ip
  2. import (
  3. "dhcp/code"
  4. "dhcp/result"
  5. "errors"
  6. "fmt"
  7. "net"
  8. )
  9. // DetectPublicIPv4 获取公网IP
  10. func DetectPublicIPv4(extra string) string {
  11. ip, err := autoDetectPublicIPv4()
  12. if err != nil {
  13. return ""
  14. }
  15. return fmt.Sprintf("%v%v", ip.String(), extra)
  16. }
  17. // autoDetectPublicIPv4 自动检测公网IP
  18. func autoDetectPublicIPv4() (net.IP, error) {
  19. ifaces, err := net.Interfaces()
  20. if err != nil {
  21. return nil, err
  22. }
  23. for i := 0; i < len(ifaces); i++ {
  24. if (ifaces[i].Flags & net.FlagUp) == 0 {
  25. continue
  26. }
  27. addrs, _ := ifaces[i].Addrs()
  28. for _, address := range addrs {
  29. ipnet, ok := address.(*net.IPNet)
  30. if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
  31. return ipnet.IP, nil
  32. }
  33. }
  34. }
  35. return nil, errors.New("unable to auto-detect public IPv4")
  36. }
  37. // GetLocalIPAndInterface 获取本地IP和网络接口
  38. func GetLocalIPAndInterface() result.Result {
  39. type IPAddInterface struct {
  40. IP string `json:"ip"`
  41. Interface string `json:"interface"`
  42. }
  43. var ipAddInterfaces []IPAddInterface
  44. // 获取所有网络接口
  45. ifaces, err := net.Interfaces()
  46. if err != nil {
  47. return result.Result{
  48. Status: false,
  49. Code: code.SystemException,
  50. Msg: "获取网络接口失败",
  51. }
  52. }
  53. for i := 0; i < len(ifaces); i++ {
  54. if (ifaces[i].Flags & net.FlagUp) == 0 {
  55. continue
  56. }
  57. addrs, _ := ifaces[i].Addrs()
  58. for _, address := range addrs {
  59. ipnet, ok := address.(*net.IPNet)
  60. if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
  61. ipface := IPAddInterface{
  62. IP: ipnet.IP.String(),
  63. Interface: ifaces[i].Name,
  64. }
  65. ipAddInterfaces = append(ipAddInterfaces, ipface)
  66. }
  67. }
  68. }
  69. return result.Result{
  70. Status: true,
  71. Code: code.SUCCESS,
  72. Msg: "获取网络接口成功",
  73. Data: ipAddInterfaces,
  74. }
  75. }