如何使用 C# 编写代码,程序化地确定我是否具有连接到指定 IP 地址和端口的服务器(TCP)的权限?
如何使用 C# 编写代码,程序化地确定我是否具有连接到指定 IP 地址和端口的服务器(TCP)的权限?
你可以使用Ping类(.NET 2.0及以上版本)
Ping x = new Ping(); PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
if(reply.Status == IPStatus.Success) Console.WriteLine("地址可访问");
在生产系统中,您可能想使用异步方法来允许取消等操作。
通常会在公开可见的服务器上禁用或阻止Ping
- teynon假设您的意思是通过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
声明字符串地址和整型端口,然后您就可以通过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;
}