加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:24:00 所属栏目:大数据 来源:网络整理
导读:我成功地运行了一个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) }} 但我想知道如何找出
我成功地运行了一个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地址)向我的服务器发送请求

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读