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?
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;
}
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.
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 eg 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!
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.