golang 通過net.UDPConn獲取UDP通信對端的IP和端口

 

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)
}

 參考:

https://stackoverflow.com/questions/24231969/how-can-i-get-clients-ip-address-on-udp-server-in-golang

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章