如何在Golang中读取UDP数据报接收的输入接口和远程套接字地址?

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

How to read both input interface and remote socket address for an UDP datagram received in Golang?

问题

PacketConn.ReadFrom()可以提供包含输入接口的ifIndex的ControlMessage

UDPConn.ReadFromUDP()返回带有数据报的源套接字地址(srcIP+srcPort)的net.UDPAddr

然而,如何同时获取输入接口的ifIndex和远程套接字地址(srcIP+srcPort)?

编辑:我已经提交了一个问题:https://github.com/golang/go/issues/14362

英文:

PacketConn.ReadFrom() can provide ControlMessage containing the ifIndex for the input interface.

UDPConn.ReadFromUDP() returns net.UDPAddr with the source socket address (srcIP+srcPort) of the datagram.

However, how to get BOTH informations: input interface ifIndex AND remote socket address (srcIP+srcPort) ?

EDIT: I have filled an issue: https://github.com/golang/go/issues/14362

答案1

得分: 1

当底层套接字是UDP时,.ReadFrom() 返回一个 *net.UDPAddr 对象作为 net.Addr 的结果。

因此,.ReadFrom() 可以用于获取输入接口(作为 ifIndex)和远程套接字的完整端点地址(net.UDPAddr 中的 IP 地址+端口)。

// c 是 *ipv4.PacketConn

n, cm, srcAddr, err := c.ReadFrom(buf)

switch srcAddr.(type) {
    case *net.UDPAddr:
        udpAddr := srcAddr.(*net.UDPAddr)
}
英文:

When the underlying socket is UDP, .ReadFrom() returns a *net.UDPAddr object as a net.Addr result.

Thus .ReadFrom() can be used go obtain both input interface (as ifIndex) and remote socket full endpoint address (IPaddr+port within net.UDPAddr).

// c is *ipv4.PacketConn

n, cm, srcAddr, err := c.ReadFrom(buf)

switch srcAddr.(type) {
    case *net.UDPAddr:
        udpAddr := srcAddr.(*net.UDPAddr)
}

huangapple
  • 本文由 发表于 2016年2月17日 04:57:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/35442824.html
匿名

发表评论

匿名网友

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

确定