PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How to get IP used by sendto function?

 October 22, 2022     ip, sockets, winapi     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing