简体   繁体   中英

How to know whether I'm connected to a network or not?

I'm using .Net 4.0 in VS 2010. I can retreive the IP Address of my machine as

string hostname = Dns.getHostName();
IPHostEntry host = Dns.getHostEntry(hostname);

Now host.AddressList is an array of IPAddresses.

I noticed that AddressList[0] contains nothing, AddressList[1] the loopback address. I'm not sure about other indices.

If I have created a server on one machine and it wants to populate its IP to client (may be the machine only), then which IP (among host.AddressList) shall I populate? Which index to use? How do I know whether I'm connected to a LAN or the internet, or not connected at all? Please clarify.

This might be a possible duplicate of this question .

Don't assume you're connected to the internet (or any other network) just due to having a valid dns server or multiple IPs. Local PCs or routers might act as the active DNS and could be available even without some internet connection or any other machines on the same network. For possible solutions, have a look at the question/answers I linked above. There are also one or two examples just to detect the presence of an active network connection.

As for detecting an active internet connection, I'd always just try to request some page on the server I want to connect to (could be combined with some update check or news display), because it might be important to be able to connect to some specific server (and not just a general internet connection).

There are several ways to do that (I think you may use a combination of [2] and [3]).

Solution 1

If you include a reference to Microsoft.VisualBasic you can use Microsoft.VisualBasic.Devices.Network.IsAvailable property to check if a network connection is available (and related events to be notified when this condition changes).

Solution 2

Import the API function to check it:

[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
}

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

Or simply use the System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() function (better solution, the only drawback is that it's supported in the Client Profile only from 4.0).

Solution 3

Ping a known host name like Google or Microsoft (this will check DNS too).

Example

Use a combination of above techniques (in this example I use the imported API but you may prefer the other one).

static class NetworkHelpers
{
    public static bool IsNetworkConnectionAvailable()
    {
        InternetConnectionState state = InternetConnectionState.INTERNET_CONNECTION_OFFLINE;
        if (!InternetGetConnectedState(ref state, 0))
            return false;

        if (state == InternetConnectionState.INTERNET_CONNECTION_OFFLINE)
            return false;

        try
        {
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingReply reply = ping.Send(KnownHostName, PingTimeout);

            return reply.Status == System.Net.NetworkInformation.IPStatus.Success;
        }
        catch (System.Net.NetworkInformation.PingException)
        {
            return false;
        }
    }

    private const string KnownHostName = "http://www.microsoft.com";
    private const int PingTimeout = 5000; // milliseconds

    [Flags]
    private 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
    }

    [System.Runtime.InteropServices.DllImport("WININET", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern bool InternetGetConnectedState(ref InternetConnectionState lpdwFlags, int dwReserved);
}

The status of the internet connection can be easily found using this:

[DllImport("wininet.dll", Charset = Charset.auto)]
private static extern bool InternetGetConnectedSate(ref InternetConnectionState_e lpdwFlags, int dwReserved);

and then for example:

if(InternetConnectionState_e.INTERNET_CONNECTION_PROXY) != 0)
{
    // do your internet stuff
}

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