1

I'm making a LAN chat application (server and client program) and I wanted to know how can I get my own computer's IP address (for the server program) and found this question.

I used the code in my program and tested it while my computer's not connected to the internet, to a LAN or any external devices and I thought that the code will throw an exception because of that (and would mean that my computer's not connected any network)... but it didn't and instead, it returned an IP Address.

Is there a way to find out if my computer's not connected to any network?

Community
  • 1
  • 1
Xel
  • 540
  • 2
  • 8
  • 27
  • 1
    Possible duplicate of [this question](http://stackoverflow.com/questions/520347/c-sharp-how-do-i-check-for-a-network-connection) – Anastasiosyal Feb 24 '12 at 10:32

3 Answers3

1

With System.Net.NetworkInformation you can gather informations about your Network interfaces. So this should help you:

public Boolean isConnected()
{
    NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface face in interfaces)
    {
        if (face.OperationalStatus == OperationalStatus.Up || face.OperationalStatus == OperationalStatus.Unknown)
        {
            // Internal network interfaces from VM adapters can still be connected 
            IPv4InterfaceStatistics statistics = face.GetIPv4Statistics();
            if (statistics.BytesReceived > 0 && statistics.BytesSent > 0)
            {
                // A network interface is up
                return true;
            }
        }
    }
    // No Interfaces are up
    return false;
}
radbyx
  • 9,352
  • 21
  • 84
  • 127
1

You can subscribe to the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged event, then evaluate the NetworkAvailabilityEventArgs.IsAvailable property.

Alternatively you can call the System.Net.NetworkInformation.GetIsNetworkAvailable() method.

Christian.K
  • 47,778
  • 10
  • 99
  • 143
0

only way to check that if you are connected to the network at any particular point of time is to check if any of your gateways are reachable at that point of time e.g. ping all the gateway's addresses and if at least one of them respond then you are really connected: if none of them responded, then your cable still may be connected but one can't say that you are connected to network!

hope this helps! cforfun!

cforfun
  • 135
  • 1
  • 11
  • 1
    @Xei sorry i haven't coded in c#, so can't give you the example here. but you should be able to call any script from c# and that script can do the job for you. e.g ping and ifconfig are two programs available mostly on all systems (or a variation of them): those two programs are sufficient to develop this logic. There are many other ways you can develop this simple logic, but using simple scripts/network tools can solve amazing problems than developing the entire logic yourself. – cforfun Feb 27 '12 at 01:41