给定服务器的IP地址和端口,如何使用C#测试与服务器的TCP连接?
问题描述:
如何通过编程方式 确定是否可以使用C#访问具有给定IP地址和端口的服务器(TCP)?
How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?
答
假设您是通过TCP套接字进行访问的:
Assuming you mean through a TCP socket:
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