Checking network status in C#
Solution 1
If you just want to check if the network is up then use:
bool networkUp
= System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
To check a specific interface's status (or other info) use:
NetworkInterface[] networkCards
= System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
To check the status of a remote computer then you'll have to connect to that computer (see other answers)
Solution 2
If you want to monitor for changes in the status, use the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
event:
NetworkChange.NetworkAvailabilityChanged
+= new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
_isNetworkOnline = NetworkInterface.GetIsNetworkAvailable();
// ...
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
_isNetworkOnline = e.IsAvailable;
}
Solution 3
First suggestion (IP connection)
You can try to connect to the IP address using something like:
IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("IP TO CHECK"), YOUR_PORT_INTEGER);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);
I suggest you to the check code of a "Chat" program. These programs manipulate a lot of IP connections and will give you a good idea of how to check if an IP is available.
Second suggestion (Ping)
You can try to ping. Here is a good tutorial. You will only need to do:
Ping netMon = new Ping();
PingResponse response = netMon.PingHost(hostname, 4);
if (response != null)
{
ProcessResponse(response);
}
Solution 4
If you're interested in the HTTP status code, the following works fine:
using System;
using System.Net;
class Program {
static void Main () {
HttpWebRequest req = WebRequest.Create(
"http://www.oberon.ch/") as HttpWebRequest;
HttpWebResponse rsp;
try {
rsp = req.GetResponse() as HttpWebResponse;
} catch (WebException e) {
if (e.Response is HttpWebResponse) {
rsp = e.Response as HttpWebResponse;
} else {
rsp = null;
}
}
if (rsp != null) {
Console.WriteLine(rsp.StatusCode);
}
}
}
Solution 5
You can check network status using
if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
//Do your stuffs when network available
}
else
{
//Do stuffs when network not available
}
Brian Clark
Updated on July 09, 2022Comments
-
Brian Clark almost 2 years
How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the 'My' structure. Thank you.
-
Brian Clark over 15 yearsThanks for the suggestions. The ping class is proving very useful.
-
redcalx over 11 yearsPing packets (ICMP echo requests) are commonly blocked by firewalls, therefore using this approach to test availability of a server on the other side of a firewall will fail in such a scenario.