I have a server with a couple of different IP addresses. At this point, each IP can recieve a UDP request, but it is always the same IP that replies, which the requesters do not like.
To make a long story short, this is all the essential code:
int sock;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
memset((char*)&serv_addr, 0, sizeof(serv_addr));
sock = socket(AF_INET, SOCK_DGRAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(PORT);
...
recvfrom(sock, buffer, BUFLEN, 0, (struct sockaddr *)&cli_addr, &clilen);
...
sendto(sock, resData, resLen, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr));
I would like to be able to specify somehow which IP is used to send back my packet (and this could differ for each and every request), but I have no idea how and if this even can be accomplished using sockets. I'm not really that experienced in this field, so all the help that I can get is greatly appreciated.
Edit below
I have found a potential solution in the accepted answer here: How to re bind a udp socket in Linux
However, a new problem emerges. How do I know which IP/interface recieved the request? So that I can respond using that IP/interface.
Typical TCP/UDP sockets binds on a particular IP/Port before doing Rx/Tx. Try using raw socket for your approach.
its rather big code, please refer the following link http://sock-raw.org/papers/sock_raw
create a raw socket - Rx via raw socket -now you will receive entire frame from L2 Tx via raw socket - transmit from L3 header after modifying relevant fields
You need to
bind()
to a local IP address, the IP of the interface that you want to use.Read this guide about
bind()
Beej's Guide To Networking#bind
I have solved my issue, and in good manner the solution must be posted! I did not use SOCK_RAW, nor did I bind my interface to a local IP or the such. This is a mixture of 100 pages on google and some stackoverflow, so I'm a bit sad that I haven't saved the links to give out the correct credits.
There might be obvious flaws in the code as I am no expert, however this is the solution I came up with and it works. I just started cleaning up the code (it gets messy when you try stuff from 100 different pages and combine them). Anyways, here it is:
Receive part:
Send part: