mdns.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package mdns
  2. import (
  3. "github.com/kptyun/KPTCOMM/comm"
  4. "net"
  5. "strconv"
  6. "strings"
  7. )
  8. const (
  9. SERVER_RECV_LEN = 20
  10. )
  11. func Mdns(servicename string, SERVER_PORT int) {
  12. sameIP := net.UDPAddr{
  13. IP: net.IPv4(0, 0, 0, 0),
  14. Port: 0,
  15. }
  16. sameint := 0
  17. maxsameint := 0
  18. netInterfaces, err := net.Interfaces()
  19. if err != nil {
  20. comm.Logger.Errorln(err)
  21. return
  22. }
  23. address := ":" + strconv.Itoa(SERVER_PORT)
  24. addr, err := net.ResolveUDPAddr("udp", address)
  25. if err != nil {
  26. comm.Logger.Errorln(err)
  27. return
  28. }
  29. conn, err := net.ListenUDP("udp", addr)
  30. if err != nil {
  31. comm.Logger.Errorln(err)
  32. return
  33. }
  34. defer conn.Close()
  35. for {
  36. // Here must use make and give the lenth of buffer
  37. data := make([]byte, SERVER_RECV_LEN)
  38. _, rAddr, err := conn.ReadFromUDP(data)
  39. if err != nil {
  40. comm.Logger.Errorln(err)
  41. continue
  42. }
  43. strData := string(data)
  44. maxsameint = 0
  45. if strings.Contains(strings.ToUpper(strData), strings.ToUpper(servicename)) {
  46. for i := 0; i < len(netInterfaces); i++ {
  47. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  48. addrs, _ := netInterfaces[i].Addrs()
  49. for _, address := range addrs {
  50. sameint = 0
  51. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  52. if ipnet.IP.To4() != nil {
  53. if ipnet.IP[12] == rAddr.IP[12] {
  54. sameint++
  55. if ipnet.IP[13] == rAddr.IP[13] {
  56. sameint++
  57. if ipnet.IP[14] == rAddr.IP[14] {
  58. sameint++
  59. if ipnet.IP[15] == rAddr.IP[15] {
  60. sameint++
  61. }
  62. }
  63. }
  64. }
  65. if sameint > maxsameint {
  66. maxsameint = sameint
  67. sameIP.IP = ipnet.IP
  68. }
  69. }
  70. }
  71. }
  72. }
  73. }
  74. if maxsameint > 0 {
  75. _, err = conn.WriteToUDP([]byte("ip:"+sameIP.IP.String()), rAddr)
  76. if err != nil {
  77. comm.Logger.Errorln(err)
  78. continue
  79. } else {
  80. comm.Logger.Infoln(rAddr.IP.String(), "查找本机")
  81. }
  82. }
  83. }
  84. }
  85. }