Windows Service来检测网络更改事件 [英] Windows Service to detect network change event

查看:51
本文介绍了Windows Service来检测网络更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C#中创建一个事件侦听器,该事件侦听器将在网络发生更改(例如新的IP地址)时让用户知道.我尝试进行研究以找到不同的方法来执行此操作,但是我没有看到如何在C#中专门执行此操作并完成我需要完成的所有任务.我正在使用此处 http://msdn提供的信息来构建侦听器.microsoft.com/en-us/library/zt39148a.aspx#Y570 ,但这对我也不起作用.轮询可能是我的最佳选择,但是如果有人可以提供帮助,将不胜感激.我正在XP和.NET 4.0上运行.

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.

推荐答案

您可以在服务中监听NetworkChange事件:

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);
        }
    }

}

有关IP地址的信息可以在NetworkInterface中找到.

Information on the IP address can be found within NetworkInterface.

要在上述服务中获取IP地址信息,应执行以下操作:

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();
}

这篇关于Windows Service来检测网络更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆