mdns.go 1.9 KB

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