6

I've two pc using VRRP for redundancy. So every PC (Linux) has a physical and a Virtual IP address.

I've a software (C++) with a client/server architecture with UDP protocol. The software bind the listen socket on "0.0.0.0" and use a new socket every time it needs to send some data to the other party. With wireshark I saw that when it sends data the source IP is the phisycal one... How can I set the source address of the sending socket to the Virtual one??

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

Napoleone1981
  • 107
  • 2
  • 10
  • Do you mean that you have two ip addresses on the same physical network card? If so that's a "virtual adapter" not a virtual IP address. You probably just need to bind to the correct address and ignore if it's virtual or not. – Jay Apr 22 '11 at 14:16
  • Possible duplicate of [How to fake source ip-address of a udp-packet?](https://stackoverflow.com/questions/2493384/how-to-fake-source-ip-address-of-a-udp-packet) – user3076936 Apr 09 '18 at 08:16

2 Answers2

9

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

  • if the socket is bound, use that source address
  • is the socket is not bound, it looks around for interfaces and selects a source address

So you need to bind(2) your socket to your desired address. For more information: "Source Address Selection" in chapter "IP Routing" of "Guide to IP Layer Network Administration with Linux".

U. Windl
  • 3,480
  • 26
  • 54
cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

i'm not sure i understand entirely your question, but in terms of writing C/C++ code on linux at low level, you can import the ip.h header from the linux kernel headers which gives you access to the low level IP packet structure. (UDP works on top of IP)

#include <linux/ip.h>

and then look at struct iphdr which is the header for every IP packet sent and that contains a saddr member which you can set programmatically to be the source address.

Liv
  • 6,006
  • 1
  • 22
  • 29
  • Ok, I try to explain better. I have a physical address and a Virtual Address (not showing with ifconfig) with the same netmask. When I send data via an UDP Socket (without bind but only connect) I'd like source address to be the Virtual IP, while with the actual code (the standard code to open a socket and send data) the source address is the physical one. I hope I've not descend to so low level code... :-) – Napoleone1981 Apr 22 '11 at 12:27
  • as i said, you can set the source address the way i described to the virtual ip. – Liv Apr 22 '11 at 12:34
  • I think this answer is too abstract. Some sample code would be quite helpful. – U. Windl Oct 25 '21 at 13:46