如何在golang上的UDP服务器上获取客户端IP地址?

时间:2014-06-15 16:59:40

标签: go udp ip-address

我在go

上成功运行了一个udp服务器
func main() {
    service := "0.0.0.0:27014"
    udpAddr, err := net.ResolveUDPAddr("udp4", service)
    checkError(err)
    conn, err := net.ListenUDP("udp", udpAddr)
    checkError(err)
    for {
        handleClient(conn)
    }
}

但我想知道如何找出谁(远程IP地址,客户端IP地址)向我的服务器发送请求

1 个答案:

答案 0 :(得分:5)

在连接模式下,您可以使用连接对象的LocalAddr()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)
ReadMsgUDP reads a packet from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the packet and the source address of the packet.

地址信息是这些方法签名中返回值的一部分。