123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package mdns
- import (
- "github.com/kptyun/KPTCOMM/comm"
- "net"
- "strconv"
- "strings"
- )
- const (
- SERVER_RECV_LEN = 20
- )
- func Mdns(servicename string, SERVER_PORT int) {
- sameIP := net.UDPAddr{
- IP: net.IPv4(0, 0, 0, 0),
- Port: 0,
- }
- sameint := 0
- maxsameint := 0
- netInterfaces, err := net.Interfaces()
- if err != nil {
- comm.Logger.Errorln(err)
- return
- }
- address := ":" + strconv.Itoa(SERVER_PORT)
- addr, err := net.ResolveUDPAddr("udp", address)
- if err != nil {
- comm.Logger.Errorln(err)
- return
- }
- conn, err := net.ListenUDP("udp", addr)
- if err != nil {
- comm.Logger.Errorln(err)
- return
- }
- 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 {
- comm.Logger.Errorln(err)
- continue
- }
- strData := string(data)
- maxsameint = 0
- if strings.Contains(strings.ToUpper(strData), strings.ToUpper(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 {
- comm.Logger.Errorln(err)
- continue
- } else {
- comm.Logger.Infoln(rAddr.IP.String(), "查找本机")
- }
- }
- }
- }
- }
|