I recently worked on a c # winform project and encountered a problem in determining whether the network is connected normally. Later, we found the following methods for your reference.
1. method 1
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Windows. Forms;
Using System. Net. Sockets;
Using System. Threading;
Namespace WindowsFormsApplication1
{
Public partial class Demo: Form
{
Public Demo ()
{
InitializeComponent ();
}
// Judge
Private void btpanduan_Click (object sender, EventArgs e)
{
// 210.192.120.228 163 Netease
String ip = this.txt ip. Text. ToString ();
Int port = Convert. ToInt32 (this.txt port. Text. ToString ());
Bool a = panduan (ip, port); // 135 indicates the service port number of the local machine.
If (a = true)
{
MessageBox. Show ("the network connection is normal! ");
}
Else
{
MessageBox. Show ("this network connection is not smooth! ");
}
}
// Asynchronous call
// Method of judgment
Public bool panduan (string ip, int port)
{
Try
{
TcpClient client = new TcpClient (ip, port );
If (client. Connected)
{
Return true;
}
Else
{
Return false;
}
}
Catch
{
Return false;
}
}
}
}
2. Use the c # ping class
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Using System. Net;
Namespace WindowsFormsApplication1
{
Public partial class Demo3: Form
{
Public Demo3 ()
{
InitializeComponent ();
}
System. Net. NetworkInformation. Ping ping = new System. Net. NetworkInformation. Ping ();
System. Net. NetworkInformation. PingReply res;
// Check the network connection
Private void btcheck_Click (object sender, EventArgs e)
{
String url = this.txt url. Text. ToString ();
Bool a = check (url );
If (a = true)
{
MessageBox. Show ("connection successful! "," Prompt information ");
}
Else
{
MessageBox. Show ("connection failed! "," Prompt information ");
}
}
Public bool check (string url)
{
Try
{
Res = ping. Send (url );
If (res. Status = System. Net. NetworkInformation. IPStatus. Success)
{
Return true;
}
Else
{
Return false;
}
}
Catch {
Return false;
}
}
}
}
From the wanglei_smartfish Column