Issue
When the sender has multiple network cards, this function sendto
chooses random ip to send the packet.
So get the ip address used by sendto
?
Code:
fd = socket(AF_INET, SOCK_DGRAM, 0);
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
Solution
It doesn't choose a random IP. It uses the OS's routing table to decide which local IP has the best chance of routing the data to the destination address. However, there is no way to query which IP sendto()
actually chose to use. You could access the OS's routing table directly and try to figure it out manually, but the better option is to just bind()
the socket to the specific IP that you want sendto()
to use as the sending IP, eg:
fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in localaddr;
memset(&localaddr, 0, sizeof(localaddr));
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.0.1"); // the desired local IP
bind(fd, (struct sockaddr*)&localaddr, sizeof(localaddr));
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
Answered By - Remy Lebeau Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.