【发布时间】:2010-09-13 06:59:04
【问题描述】:
我如何以编程方式确定我是否可以使用 C# 访问具有给定 IP 地址和端口的服务器 (TCP)?
【问题讨论】:
-
有必要澄清一下。 “访问”是什么意思?您是否尝试连接到目标机器上的特定端口?
-
我已将问题更新为更具体(给定 IP+端口的 TCP 访问)
标签: c# networking
我如何以编程方式确定我是否可以使用 C# 访问具有给定 IP 地址和端口的服务器 (TCP)?
【问题讨论】:
标签: c# networking
您可以使用 Ping 类(.NET 2.0 及更高版本)
平 x = 新平(); PingReply 回复 = x.Send(IPAddress.Parse("127.0.0.1")); 如果(回复.Status == IPStatus.Success) Console.WriteLine("地址可访问");您可能希望在生产系统中使用异步方法来允许取消等。
【讨论】:
It is common practice to disable or block Ping on publicly visible servers
假设您的意思是通过 TCP 套接字:
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
欲了解更多信息:http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
【讨论】:
声明字符串地址和 int 端口,您就可以通过 TcpClient 类进行连接了。
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
【讨论】:
应该这样做
bool ssl;
ssl = false;
int maxWaitMillisec;
maxWaitMillisec = 20000;
int port = 555;
success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}
【讨论】: