How to set the source address when sending using a UDP socket

I have two computers using VRRP for backup. Therefore, each PC (Linux) has a physical and virtual IP address.

I have software (C ++) with client / server architecture with UDP protocol. The software binds the auditory socket to "0.0.0.0" and uses a new socket whenever necessary to send some data to the other side. With wirehark, I saw that when it sends data, the source IP address is physical ... How to set the source address of the sending socket to virtual?

NOTE: Whit ifconfig I only see eth0 with a physical address ...

+4
source share
2 answers

When the kernel needs to send something through a socket, it performs the following steps

  • if the socket is connected, use this source address
  • - the socket is not connected, it looks through the interfaces and selects the source address

So you need to bind(2) your socket to your desired address. For more information: Select a source address .

+7
source

I'm not sure I fully understand your question, but from the point of writing low-level C / C ++ code on Linux, you can import the ip.h header from the Linux kernel headers, giving you access to the low-level IP packet structure. (UDP works over IP)

 #include <linux/ip.h> 

and then look at struct iphdr , which is the header for each IP packet sent and contains the saddr element, which you can programmatically specify as the source address.

0
source

All Articles