long story short
背景:我的工作台器有俩网卡/ip,现在写了个socket的程序跟局域网里的另一台机器通信。
假设我的俩ip为:172.16.10.41(有线);192.168.1.14(无线)
现在另一台机器(ip:172.16.10.47)拿服务端程序开启监听,我的机器连接那台机器,服务端拿到通信套接字 点出RemoteEndPoint就是我这边的ip 现在就想知道如何指定这个ip(默认连接都是我这边的有线ip 即:172.16.10.41)
服务端代码:
Socket socketWatch =
new
Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(
"172.16.10.47"
);
IPEndPoint endpoint =
new
IPEndPoint(address, 2000);
socketWatch.Bind(endpoint);
socketWatch.Listen(10);
MessageBox.show(
"服务端开始监听..."
);
Socket sokConnection = socketWatch.Accept();
//接收客户端连接请求
MessageBox.show(
"连接成功,客户端IP为:"
+ sokConnection.RemoteEndPoint.ToString());
//这里收到的总是客户端的有线IP
IPAddress address = IPAddress.Parse(
"172.16.10.47"
);
IPEndPoint endpoint =
new
IPEndPoint(address, 2000);
Socket socketClient =
new
Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.Connect(endpoint);
//向服务端发送连接请求(这里默认就用了有线连接)
客户端用binding ip就可以了
IPAddress[] ipAddress = Dns.GetHostAddresses(_host);
IPEndPoint remoteEP = newIPEndPoint(ipAddress[0], _port);
socketClient = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (_ClientIP != null && _ClientIP != ""){
IPEndPoint localIPE = newIPEndPoint(IPAddress.Parse(_ClientIP), 0);
socketClient.Bind(localIPE);
}
socketClient.BeginConnect(remoteEP, newAsyncCallback(ConnectCallback), socketClient);
connectDone.WaitOne();
这个问题是根据你本机的路由表来决定的,不能直接指定本机用哪个IP通信。除非你自己编辑自己机器的路由表才有可能实现。
IPAddress.Any
new
IPEndPoint(address, 2000) =>
new
IPEndPoint(IPAddress.Any, 2000)