conn.RemoteAddr()返回的是空值,需要使用下列函数,在返回值中有地址
func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
ReadFrom implements the PacketConn ReadFrom method.
func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
ReadFromUDP reads a UDP packet from c, copying the payload into b. It returns the number of bytes copied into b and the return address that was on the packet.
func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
func udpProcess(conn *net.UDPConn) {
// 最大读取数据大小
data := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(data)
if err != nil {
fmt.Println("failed read udp msg, error: " + err.Error())
}
str := string(data[:n])
fmt.Println("receive from client, data:" + str)
<-limitChan
fmt.Println(addr.IP)
}
参考: