Method 1:
How to check if your computer is connected to the Internet with C #. it's much more easier that other tutorials I 've seen in other sites. in deed, We're re going to use a simple API function internetgetconnectedstate, to return a Boolean variable.
This function takes two arguments:
The first one is an integer used with out keyword, that means that after calling the function, the variable will contain in an interger that describes the connection state (use of a modem, use of a proxy, offline mode ...). note that you must refer to www.msdn.com for more information about that.
The second one is a reserved variable that must be set to 0.
In this tutorial, we'll create a class with a static function that returns true if connected and false if not, using our API function in private State.
Check this out:
Using system; Using system. runtime; Using system. runtime. interopservices; Public class internetcs {
// Creating the extern function... [Dllimport ("wininet. dll")] Private extern static bool internetgetconnectedstate (INT out description, int reservedvalue );
// Creating a function that uses the API function... Public static bool isconnectedtointernet () {
Int DESC; Return internetgetconnectedstate (Out DESC, 0 );
}
} |
Method 2: Add a class library (System. net. networkinformation)
# Region method 2
/// <Summary>
/// Check whether the IP address or domain name can be accessed using the TCP/IP protocol (using the ping command). True indicates that the Ping is successful, and false indicates that the ping fails.
/// </Summary>
/// <Param name = "stripordname"> enter a parameter, indicating the IP address or domain name. </param>
/// <Returns> </returns>
Public static bool pingipordomainname (string stripordname)
{
Try
{
Ping objpingsender = new Ping ();
Pingoptions objpinoptions = new pingoptions ();
Objpinoptions. dontfragment = true;
String data = "";
Byte [] buffer = encoding. utf8.getbytes (data );
Int inttime out = 120;
Pingreply objpinreply = objpingsender. Send (stripordname, inttimeout, buffer, objpinoptions );
String strinfo = objpinreply. Status. tostring ();
If (strinfo = "success ")
{
Return true;
}
Else
{
Return false;
}
}
Catch (exception)
{
Return false;
}
}
# Endregion