当前位置: 编程技术>.net/c#/asp.net
socket不能选择本地IP连接的解决方法
来源: 互联网 发布时间:2014-08-30
本文导语: 有没有想到用程序自动绑定本地的任何IP地址呢,如果你恰有此意,那么请仔细阅读本文。 客户端要通过socket与服务器端进行通信,可是客户端服务器上是双ip地址(比方是192.168.1.10和192.168.1.20),可是 服务器端只允许192.168.1.2...
有没有想到用程序自动绑定本地的任何IP地址呢,如果你恰有此意,那么请仔细阅读本文。
客户端要通过socket与服务器端进行通信,可是客户端服务器上是双ip地址(比方是192.168.1.10和192.168.1.20),可是 服务器端只允许192.168.1.20进行通信,进行了ip限制,在客户端上192.168.1.10是主ip,192.168.1.20是从ip,如果简单通过socket建立连接,程序默认会以192.168.1.10进行通信,这样服务器端会拒绝。
怎么解决这个问题呢?
例如本机IP地址为:
192.168.1.205,192.168.1.204,192.168.1.203
实现:
代码示例:
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
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
例子:
代码示例:
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); //建立长连接
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); //建立长连接