如何从 Linux 上的特定接口发送 UDP 数据包?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4584908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I send UDP packet from a specific interface on Linux?
提问by Hymanhab
How do I send UDP packet from a specificinterface on Linux using C? Should I use bind? Is it possible to send UDP from the interface not having IP address?
如何使用 C从Linux 上的特定接口发送 UDP 数据包?我应该使用绑定吗?是否可以从没有 IP 地址的接口发送 UDP?
Thanks.
谢谢。
采纳答案by Hasturkun
You can bind a socket to a specific interface by using the SO_BINDTODEVICE
socket option, however this requires root privileges.
您可以使用SO_BINDTODEVICE
socket 选项将套接字绑定到特定接口,但这需要 root 权限。
Alternately, you can set the IP_PKTINFO
option, and use sendmsg
for sending, setting the in_pktinfo
's ipi_ifindex
to the index of your interface.
或者,您可以设置IP_PKTINFO
选项,并sendmsg
用于发送,将in_pktinfo
's设置为ipi_ifindex
界面的索引。
回答by Oswald
Use bind. You cannot send UDP packets via an interface that does not have an IP address, because UDP uses the Internet Protocol and the Internet Protocol requires an IP address.
使用绑定。您不能通过没有 IP 地址的接口发送 UDP 数据包,因为 UDP 使用 Internet 协议,而 Internet 协议需要一个 IP 地址。
回答by Stephane
You need to use socket option IP_MULTICAST_IF.
您需要使用套接字选项 IP_MULTICAST_IF。
See here: Multicast-HOWTO-6.html
请参阅此处:Multicast-HOWTO-6.html