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.
Well, you would try to connect to the specific ip, and handle denies and timeouts.
Look at the TcpClient class in the System.Net.Sockets namespace.
First suggestion (IP Connexion)
You can try to connect to the IP 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 check code for "Chat" program. These program manipulate a lot of IP connection 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);
}
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);
}
}
}
Regards, tamberg
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)
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;
}