Socket cannot select local IP connection problem how to solve

  • 2020-05-07 20:20:25
  • OfStack

Now I've got a problem with a stick in my hand. That's it!
My client through socket communicate with the server, but the client is double ip address on the server (for example is 192.168.1.10 and 192.168.1.20), but the server allows only 192.168.1.20 communicate, ip limit, on the client side 192.168.1.10 is main ip, 192.168.1.20 ip, if I simply by socket connection is established, the application will default to 192.168.1.10 communicate, So the server side will reject, should I write to be able to solve this problem?

Don't do it manually, do it automatically, and bind to any IP address locally.
For example, the local IP address is:
192.168.1.205, 192.168.1.204, 192.168.1.203
The results are:
C:\ > netstat -an | find "59.39.71.94"
TCP 192.168.1.205:2302 59.39.71.94:80 ESTABLISHED
C:\ > netstat -an | find "59.39.71.94"
TCP 192.168.1.203:12302 59.39.71.94:80 ESTABLISHED
C:\ > netstat -an | find "59.39.71.94"
TCP 192.168.1.204:7802 59.39.71.94:80 ESTABLISHED
If convenient, give a code! Thank you very much!
 
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 string serverIp = "59.39.71.94"; 
int serverProt = 80; 
string clientIp = "192.168.1.104"; 
int clientProt = 8012; 
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
var ipHostEntry = Dns.GetHostEntry(serverIp); 
var ipEndPoint = new IPEndPoint(ipHostEntry.AddressList[0], serverProt); 
var address = IPAddress.Parse(clientIp); 
if (address != null) 
{ 
var localEp = new IPEndPoint(address, clientProt); 
socket.Bind(localEp); 
} 
socket.Connect(ipEndPoint); // Make long connections  

The above code can fully achieve the above function.

Related articles: