Check the network connection status

Source: Internet
Author: User
The following sectionCodeReturns the network connection status of the current computer.
[Dllimport (" Wininet. dll ")]
Private Static Extern Bool Internetgetconnectedstate ( Ref Uint Connected, Uint Reserved );

Static Uint Uconnection = 0x20;

/// <Summary>
/// Returns true if it have detected an active Internet connection.
/// </Summary>
Public Static Bool Hasinternetconnection
{
Get { Return Internetgetconnectedstate ( Ref Uconnection, 0 );}
}

In addition:

To check for
Internet connection in. net, we can use getisnetworkavailable Method
Defined in the system. net. Network-Information namespace. But it returns
A boolean value that denotes whether any network connection is
Available and does not say about Internet connectivity. To make sure we
Also have Internet access, the reliable method is to attempt to ping
Host

...
UsingSystem. net. networkinformation;
...
Public BoolIsconnectedtointernet ()
{
StringHost =Http://www.c-sharpcorner.com;
BoolResult =False;
PingP =New Ping();
Try
{
PingreplyReply = P. Send (host, 3000 );
If(Reply. Status =Ipstatus. Success)
Return True;
}
Catch{}
ReturnResult;
}

Or we can use a simple API function internetgetconnectedstate. This function takes two arguments:

TheFirst oneIs an integer usedOut
Keyword, which means that after calling the function, the variable will
Contain an integer that describes the connection state.

TheSecond oneIs a reserved variable that must be set to 0.

Using System;
Using System. runtime;
Using System. runtime. interopservices;
Public Class Internetcs
{
// Creating the extern function...
[Dllimport ("wininet. dll")]
Private Extern Static Bool Internetgetconnectedstate ( Out Int Description, Int Reservedvalue );
// Creating a function that uses the API function...
Public Static Bool Isconnectedtointernet ()
{
Int DESC;
Return Internetgetconnectedstate ( Out DESC, 0 );
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.