How to set source address when sending using and UDP socket

允我心安 提交于 2020-11-28 08:13:53

问题


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...


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5755265/how-to-set-source-address-when-sending-using-and-udp-socket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!