12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package mdns
- import (
- "fmt"
- "net"
- "os"
- "strconv"
- "strings"
- )
- const (
- SERVER_RECV_LEN = 20
- )
- func Mdns(servicename string,SERVER_PORT int) {
- // flag.StringVar(&servicename, "service", "getip", "ServiceName")
- // flag.IntVar(&SERVER_PORT, "port", 5354, "Port")
- // flag.Parse()
- sameIP := net.UDPAddr{
- IP: net.IPv4(0, 0, 0, 0),
- Port: 0,
- }
- sameint := 0
- maxsameint := 0
- netInterfaces, err := net.Interfaces()
- if err != nil {
- fmt.Println("net.Interfaces failed, err:", err.Error())
- os.Exit(1)
- }
- address := ":" + strconv.Itoa(SERVER_PORT)
- addr, err := net.ResolveUDPAddr("udp", address)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- conn, err := net.ListenUDP("udp", addr)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- defer conn.Close()
- for {
- // Here must use make and give the lenth of buffer
- data := make([]byte, SERVER_RECV_LEN)
- _, rAddr, err := conn.ReadFromUDP(data)
- if err != nil {
- // fmt.Println(err)
- continue
- }
- strData := string(data)
- maxsameint = 0
- if strings.Contains(strData, servicename) {
- for i := 0; i < len(netInterfaces); i++ {
- if (netInterfaces[i].Flags & net.FlagUp) != 0 {
- addrs, _ := netInterfaces[i].Addrs()
- for _, address := range addrs {
- sameint = 0
- if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
- if ipnet.IP.To4() != nil {
- if ipnet.IP[12] == rAddr.IP[12] {
- sameint++
- if ipnet.IP[13] == rAddr.IP[13] {
- sameint++
- if ipnet.IP[14] == rAddr.IP[14] {
- sameint++
- if ipnet.IP[15] == rAddr.IP[15] {
- sameint++
- }
- }
- }
- }
- if sameint>maxsameint{
- maxsameint=sameint
- sameIP.IP = ipnet.IP
- }
- }
- }
- }
- }
- }
- if maxsameint>0{
- _, err = conn.WriteToUDP([]byte("ip:" + sameIP.IP.String()), rAddr)
- if err != nil {
- // fmt.Println(err)
- continue
- }
- }
- }
- }
- }
|