【问题标题】:how can i get clients ip address on UDP server in golang?如何在 golang 的 UDP 服务器上获取客户端 IP 地址?
【发布时间】:2014-06-15 16:59:39
【问题描述】:

我在运行中成功运行了一个 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 地址)向我的服务器发送请求

【问题讨论】:

    标签: go udp ip-address


    【解决方案1】:

    在连接模式下,您可以使用连接对象的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.
    

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

    【讨论】:

    • 谢谢 Didier,我正在使用 ReadFromUDP,addr.IP 返回远程 IP 地址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多