英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论