简体   繁体   中英

check whether Internet connection is available with C#

What is the easiest way to check whether internet connection is available programatically?

EDIT: As suggested I tried using the following method, but it is always returning true.

[Flags]
enum InternetConnectionState : int
{
    INTERNET_CONNECTION_MODEM = 0x1,
    INTERNET_CONNECTION_LAN = 0x2,
    INTERNET_CONNECTION_PROXY = 0x4,
    INTERNET_RAS_INSTALLED = 0x10,
    INTERNET_CONNECTION_OFFLINE = 0x20,
    INTERNET_CONNECTION_CONFIGURED = 0x40
}

class Program
{
    [DllImport("WININET", CharSet = CharSet.Auto)]
    static extern bool InternetGetConnectedState(ref InternetConnectionState lpdwFlags, int dwReserved);

static void Main(string[] args)
{
    InternetConnectionState flags = 0;
    bool isConnected = InternetGetConnectedState(ref flags, 0);
    Console.WriteLine(isConnected);
    //Console.WriteLine(flags);
    Console.ReadKey();
}
}

Additional Info (if it helps): I access internet over a shared wifi network.

Here is the Windows API you can call into. It's in wininet.dll and called InternetGetConnectedState .

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 ) ;
    }
}

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt . This file is a plain-text file and contains only the text 'Microsoft NCSI'. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

You can check for a network connection using this in .NET 2.0+

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

This will probably just return true for local networks, so it may not work for you.

here is the best solution I found so far:

public static bool isConnected()
    {
        try
        {
            string myAddress = "www.google.com";
            IPAddress[] addresslist = Dns.GetHostAddresses(myAddress);

            if (addresslist[0].ToString().Length > 6)
            {
                return true;
            }
            else
                return false;

        }
        catch
        {
            return false;
        }

    }

usage:

if(isConnected())
{
    //im connected to the internet
}
else
{
    //not connected
}

This is a question where the answer really is "it depends". Because it depends on why you want to check and for what kind of connectivity? Do you want to be able to access certain websites/services over http? Send smtp mail? Do dns lookups?

Using a combination of the previous answers is probably the way to go - first use the wininet api from colithium's answer to check if a connection of any kind is available.

If it is, try a couple of dns lookups (see System.Net.Dns ) for either the resources you're interested in or some popular big websites (google, altavista, compuserve, etc...).

Next, you can try pinging (see Roger Willcocks' answer) and/or establishing a socket connection to the same sites. Note that a failed ping could just mean that firewall rules don't allow you to ping.

If you can be more specific as to why you want to check it will be easier to provide an answer that covers your requirements...

Easiest way is to probably check if they can download a file from the web that you know is available. Use the following code to download google's homepage.

WebClient Client = new WebClient ();
String Response;
Response = Client.DownloadString("http://www.google.com");

You should probably wrap that in a Try .... Catch to catch the exception that is thrown when it can't establish a connection.

Network Awareness in Windows XP

Network Awareness in Windows Vista and Windows 7

Of course this does not guarantee the web site you plan to visit is not blocked by cooperative firewall rules, the API just checking if a pre-defined web site is reachable .

There are some other options too.

The InfoPath library exposes the "IsDestinationReachable" method, which is a wrapper for the Win API method of the same name. (Looks like Vista doesn't support it)

However, I believe from the Docs that it depends on something like PING, so not necessarily a good test.

Vista + say use the "Network List Manager"

@colithium Google might not be down, but things can also fail out if the DNS lokup interval exceeds the timeout. Not uncommon at home here in NZ, first try fails, second succeeds because the data has propogated back to the ISP DNS or your router cache by the time the second request is done.

Alternatively you can use DNS lookup to check internet connectivity. This method is faster than Ping method.

public static bool DnsTest()
    {
        try
        {
            System.Net.IPHostEntry ipHe =
                System.Net.Dns.GetHostByName("www.google.com");
            return true;
        }
        catch
        {
            return false;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM