给定服务器的 IP 地址,如何使用 C# 测试与服务器的连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/136615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I test a connection to a server with C# given the server's IP address?
提问by
How can I programmaticallydetermine if I have access to a server with a given IP address using C#?
如何使用 C# 以编程方式确定我是否可以访问具有给定 IP 地址的服务器?
采纳答案by GEOCHET
Assuming you mean through a TCP socket:
假设您的意思是通过 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
}
}
For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
有关更多信息:http: //msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
回答by Tigraine
Declare string address and int port and you are ready to connect through the TcpClient class.
声明字符串地址和 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();
}
回答by Learning
This should do it
这应该做
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;
}
回答by Kepboy
You could use the Ping class (.NET 2.0 and above)
您可以使用 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("Address is accessible");
You might want to use the asynchronous methods in a production system to allow cancelling, etc.
您可能希望在生产系统中使用异步方法来允许取消等。