how can i get clients ip address on UDP server in golang?

huangapple go评论93阅读模式
英文:

how can i get clients ip address on UDP server in golang?

问题

我在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地址)向我的服务器发送了请求。

英文:

I run a udp server successfully on go

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

But i Wanted to know how can i find out who(remote ip address, Client ip address) send request to my server

答案1

得分: 8

在连接模式下,您可以使用连接对象的LocalAddr()RemoteAddr()方法。

在断开连接(即经典)模式下,您可以使用以下方法之一通过数据报本身获取地址信息:

  • func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
    ReadFrom实现了PacketConn的ReadFrom方法。

  • func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
    ReadFromUDP从c中读取一个UDP数据包,将有效负载复制到b中。它返回复制到b中的字节数以及数据包上的返回地址。

  • func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
    ReadMsgUDP从c中读取一个数据包,将有效负载复制到b中,并将相关的带外数据复制到oob中。它返回复制到b中的字节数,复制到oob中的字节数,数据包上设置的标志以及数据包的源地址。

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

英文:

In connected mode, you can use the LocalAddr() and RemoteAddr() methods of the connection object.

In disconnected (i.e. classical) mode, you get the address information with the datagram itself using one of the following methods:

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.

The address information is part of the return values in the signature of these methods.

huangapple
  • 本文由 发表于 2014年6月16日 00:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/24231969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定