C#如何连接公共IP

时间:2017-02-22 14:19:22

标签: c# sockets tcp

您好我在学习如何使用套接字编写应用程序,有我的问题。我现在如何在局域网中建立连接,我的意思是......我会将我的客户端应用程序发送给我的朋友,他将能够连接到我的服务器。 有代码:

客户:

Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

sck.Bind(new IPEndPoint(IPAddress.Parse("xx.xx.31.87"), 56597));
sck.Listen(100);//maksymalna ilosc polaczen oczekujacych

Socket accepted = sck.Accept();
byte[] Buffer = new byte[accepted.SendBufferSize];

int bytesRead = accepted.Receive(Buffer);


byte[] formatted = new byte[bytesRead];


for (int i = 0; i < bytesRead; i++)
     formatted[i] = Buffer[i];


string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");

Console.Read();

sck.Close();

服务器:

Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

sck.Bind(new IPEndPoint(IPAddress.Parse("xx.xx.31.87"), 56597)); //yes i censored ip.
sck.Listen(100);//maksymalna ilosc polaczen oczekujacych

Socket accepted = sck.Accept();
byte[] Buffer = new byte[accepted.SendBufferSize];

int bytesRead = accepted.Receive(Buffer);


byte[] formatted = new byte[bytesRead];


for (int i = 0; i < bytesRead; i++)
        formatted[i] = Buffer[i];


string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");

Console.Read();

sck.Close();

我做了端口转发,但是当我想写IPEndPoint我的地址时,这给我的错误就像无效的ip。

1 个答案:

答案 0 :(得分:0)

尝试通过客户端和服务器上的DNS解析来设置端点

IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 56597);

    Socket listener = new Socket(AddressFamily.InterNetwork,  
        SocketType.Stream, ProtocolType.Tcp );  

如果在路由器和/或防火墙后面,请确保在客户端和服务器上完成端口转发。

看看MS示例:

C# Sockets over the internet有一些针对互联网套接字的故障排除提示!