Using system;
Using system. Collections. Generic;
Using system. text;
Using system. IO;
Using system. net. networkinformation;
Using system. Threading;
Namespace manager. Common
{
Public static class netcommon {
/// <Summary>
/// Verify the correctness of the IP address string
/// </Summary>
/// <Param name = "Strip"> ip address string to be verified </param>
/// <Returns> the format is correct. The format is true. Otherwise, the format is false. </returns>
Public static bool checkipaddr (string strip)
{
If (string. isnullorempty (strip ))
{
Return false;
}
// Keep the information to return
Bool Bres = true;
Int itmp = 0; // keep each integer separated "."
String [] ipsplit = strip. Split ('.');
If (ipsplit. Length <4 | string. isnullorempty (ipsplit [0]) |
String. isnullorempty (ipsplit [1]) |
String. isnullorempty (ipsplit [2]) |
String. isnullorempty (ipsplit [3])
{
Bres = false;
}
Else
{
For (INT I = 0; I <ipsplit. length; I ++)
{
If (! Int. tryparse (ipsplit [I], out itmp) | itmp <0 | itmp> 255)
{
Bres = false;
Break;
}
}
}
Return Bres;
}
/// <Summary>
/// Verify that an IP address can be pinged
/// </Summary>
/// <Param name = "Strip"> IP address to be verified </param>
/// <Returns> whether to connect: true No: false </returns>
Public static bool testnetconnectity (string strip)
{
If (! Netutil. checkipaddr (strip ))
{
Return false;
}
// For Windows L2TP VPN and non-Windows VPN, ping the VPN Server to determine whether the VPN Server can be connected.
Ping pingsender = new Ping ();
Pingoptions Options = new pingoptions ();
// Use the default TTL value which is 128,
// But change the fragmentation behavior.
Options. dontfragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
String data = "testtesttesttesttesttesttest ";
Byte [] buffer = encoding. ASCII. getbytes (data );
Int timeout = 120;
Pingreply reply = pingsender. Send (strip, timeout, buffer, options );
Return (reply. Status = ipstatus. Success );
}
/// <Summary>
/// Check whether an IP address can be pinged several times in a row
/// </Summary>
/// <Param name = "Strip"> Ping the IP address </param>
/// <Param name = "waitsecond"> interval, in seconds </param>
/// <Param name = "itesttimes"> Number of tests </param>
/// <Returns> whether it can be connected </returns>
Public static bool testnetconnected (string strip, int waitsecond, int itesttimes)
{
For (INT I = 0; I <itesttimes-1; I ++)
{
If (testnetconnectity (strip ))
{
Return true;
}
Thread. Sleep (waitsecond * 1000 );
}
Return testnetconnectity (strip );
}
}