How do I send UDP packet from a specific interface on Linux?
13,250
Solution 1
You can bind a socket to a specific interface by using the SO_BINDTODEVICE
socket option, however this requires root privileges.
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.
Solution 2
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.
Related videos on Youtube
Author by
jackhab
Updated on May 14, 2022Comments
-
jackhab about 2 years
How do I send UDP packet from a specific interface on Linux using C? Should I use bind? Is it possible to send UDP from the interface not having IP address?
Thanks.
-
nategoose over 13 yearsUnless you send them as raw packets.
-
Oswald over 13 years@nategoose That would be cheating.
-
jackhab over 13 yearsBind does not help. The source IP of the UDP packet is correct (i.e. it's the IP of the interface I'm trying to send from) but the packet itself goes from the default interface.
-
Hasturkun over 13 yearsWouldn't that only work for multicast? (also, appears to require an address)
-
Hasturkun over 13 years@Jack: You probably have a misconfigured routing table.
-
Hi-Angel over 9 yearsDon't you know: is it a crossplatform way? E.g. would it work this way on Windows®?
-
Hasturkun over 9 years@Hi-Angel: I haven't tried it, but apparently you can use the
IPPROTO_IP
IP_UNICAST_IF
socket option on Windows. This option takes an interface index, and should also work on current Linux systems (was added in 2012 and is present in Linux v3.4). -
Hi-Angel over 9 yearsHmm, interesting… I didn't found a mention about the option in GNU/Linux docs, but found a short note that it was added to help WINE project. I hope the WINE project aware of it :D
-
Hi-Angel over 9 yearsOkay, I found a mails when a wine developer requested the feature, and some patch, possibly from wine developer too. But about was it implemented it the WINE or not, I found only this patch. Not sure what it does, but I am suppose that it checks if the linux kernel defined but
IP_UNICAST_IF
not, so fall back to old implementation. If suppose that WINE developers uses up-to-date kernel, then in all the new WINE versions used the real kernel option. -
Joseph Wahba over 7 yearsCould you please have a look on my question ? stackoverflow.com/questions/41192809/…
-
Joseph Wahba over 7 yearsCould you please have a look on my question ? stackoverflow.com/questions/41192809/…
-
Compholio almost 3 yearsYes, I implemented
IP_UNICAST_IF
for Wine and it's been supported since Linux 3.3.