.NET
Network Interface Status Event
leo21c
2023. 5. 24. 19:03
.Net에서 네트워크 인터페이스의 상태를 이벤트로 전달 받을 수 있는 핸들러가 존재한다.
NetworkChange Class (System.Net.NetworkInformation)
Allows applications to receive notification when the Internet Protocol (IP) address of a network interface, also called a network card or adapter, changes.
learn.microsoft.com
아래 예제를 실행해서 LAN 케이블을 빼보면 바로 이벤트가 발생되어 전달 받는 것을 확인 할 수 있다.
기존에는 NetworkInterface 클래스를 이용해서 아답터의 OperationalStatus를 확인 하는 Thread를 만들어서 연결 상태를 확인 했었다.
이렇게 할 경우에는 Thread 주기 때문에 즉각적인 상태를 확인 하기 어려웠다.
using System;
using System.Net;
using System.Net.NetworkInformation;
namespace Examples.Net.AddressChanges
{
public class NetworkingExample
{
public static void Main()
{
NetworkChange.NetworkAddressChanged += new
NetworkAddressChangedEventHandler(AddressChangedCallback);
Console.WriteLine("Listening for address changes. Press any key to exit.");
Console.ReadLine();
}
static void AddressChangedCallback(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface n in adapters)
{
Console.WriteLine(" {0} is {1}", n.Name, n.OperationalStatus);
}
}
}
}
소스 코드는 정말 간단하다.
확인 결과 LAN 포트에서 케이블을 분리함과 거의 동시에 이벤트를 받는 것을 확인 할 수가 있었다.
LIST