20

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
  • 275
  • 1
  • 2
  • 6

7 Answers7

42

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)

Yona
  • 9,392
  • 4
  • 33
  • 42
17

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;
}
Carsten
  • 11,287
  • 7
  • 39
  • 62
CCrawford
  • 271
  • 2
  • 3
7

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);
}
Community
  • 1
  • 1
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • Thanks for the suggestions. The ping class is proving very useful. – Brian Clark Nov 24 '08 at 18:15
  • 4
    Ping 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. – redcalx Jan 31 '13 at 14:28
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);
        }
    }

}
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
tamberg
  • 1,987
  • 14
  • 23
3

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

}
Amit Kumawat
  • 574
  • 5
  • 11
1

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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
-2

My idea was to have a static class/Module to do the monitoring on a spereate thread. A simple DNS resolve will ensure if your network is up and running. Beats ping IMO.

Imports System.Net

Public Module Network_Monitor

Private InsideWorkNet As Boolean = vbFalse
Private Online_Status As Boolean = vbFalse
Private CurrentWorkIPAddress As New IPHostEntry
Private WithEvents Timer_Online_Check As New Timers.Timer With {.Interval = 5000, .Enabled = True, .AutoReset = True}


Public ReadOnly Property GetOnlineStatus() As String

    Get
        Return Online_Status
    End Get

End Property


Public Sub Initialize()

    Set_Online_Status()
    Timer_Online_Check.Start()

End Sub


Public Sub Set_Online_Status()

    If My.Computer.Network.IsAvailable Then
        Try
            Dim DNSTest As IPHostEntry = Dns.GetHostEntry("google.com")
            If DNSTest.AddressList.Length > 0 Then
                Online_Status = True
            Else : Online_Status = False

            End If

        Catch ex As System.Net.Sockets.SocketException

            Online_Status = False

        End Try
    End If

End Sub


Private Sub Timer_Online_Check_Elaspsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs) Handles Timer_Online_Check.Elapsed
    Set_Online_Status()
End Sub

Public Sub Detect_Work_Network()

    If Online_Status = True Then

        Dim WorkIP As IPHostEntry = New IPHostEntry()

        Try
            WorkIP = Dns.GetHostEntry("serverA.myworkdomain.local")
            If WorkIP.AddressList.Length > 0 Then

                InsideWorkNet = True
                CurrentWorkIPAddress = WorkIP
                'MessageBox.Show(WorkIP.HostName.ToString(), "WorkIP", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Sockets.SocketException

            Try
                WorkIP = Dns.GetHostEntry("serverA.myworkdomain.com")
                If WorkIP.AddressList.Length > 0 Then

                    InsideWorkNet = False
                    CurrentWorkIPAddress = WorkIP
                    ' MessageBox.Show(WorkIP.HostName.ToString(), "WorkIP", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
            Catch ey As Sockets.SocketException

            End Try
        End Try
    End If

End Sub

Public Function GetWorkServerName() As String
    If InsideWorkNet = True Then
        Return "serverA.myworkdomain.local"
    Else : Return "serverA.myworkdomain.com"
    End If


End Function



End Module

I also had to determine if I was inside or outside of my work network. Different servers on each side of the firewall for the app to talk to.