user1410462
user1410462

Reputation: 21

Windows Service to detect network change event

I need to create an event listener in C# that will let the user know when there is a network change (like a new IP address). I've tried doing research to find different ways to do this but I didn't see how to specifically do it in C# and accomplish all the tasks that I need done. I'm building a listener using the info provided here http://msdn.microsoft.com/en-us/library/zt39148a.aspx#Y570 but this didn't work for me either. Polling may be the best option for me but if someone could help out with this, it would be greatly appreciated. I'm operating on XP and .NET 4.0.

Upvotes: 1

Views: 6912

Answers (1)

Dave Lewis
Dave Lewis

Reputation: 153

You can just listen for NetworkChange events within your service:

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkAddressChanged);
    }

    protected override void OnStop()
    {
    }

    private void NetworkAddressChanged(object sender, EventArgs e)
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface n in adapters)
        {
            EventLog.WriteEntry("NetworkMonitor",String.Format("{0} is {1}", n.Name, n.OperationalStatus),EventLogEntryType.Warning);
        }
    }

}

Information on the IP address can be found within NetworkInterface.

To get IP address information in the above service something like this should do the trick:

IPInterfaceProperties adapterProperties = n.GetIPProperties();
IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;
foreach (IPAddress address in addresses)
{
    //do something with address.ToString();
}

Upvotes: 4

Related Questions