Get All Local Network Interface Card (NIC) C# Source Code

Yeah, actually i’m back to blogger activities… This is the part of my next projects, M-NIC Projects. The goal is to get all information of our network interface card (NIC) information such as IP addresses, link speed, name, etc. So after doing some head-to-head within some programming languages, my choices is C# .NET, because i think it’s easiest way to get that. The result is something like below, i retrieve all of my NIC which status is UP

Name            : Wireless Network Connection 2
Type            : Wireless80211
Status          : Up
Speed           : 4294967295
Description     : Microsoft Virtual WiFi Miniport Adapter
InterNetworkV6  : fe80::e1cf:b2ee:f5c7:e23e%31
InterNetwork    : 192.168.2.1
=======================================
Name            : Local Area Connection
Type            : Ethernet
Status          : Up
Speed           : 100000000
Description     : Atheros AR8152 PCI-E Fast Ethernet Controller
InterNetwork    : 192.168.1.3
=======================================
Name            : Loopback Pseudo-Interface 1
Type            : Loopback
Status          : Up
Speed           : 1073741824
Description     : Software Loopback Interface 1
InterNetworkV6  : ::1
InterNetwork    : 127.0.0.1
=======================================

And here is the code:

static void Main(string[] args)
{
    NetworkInterface[] ifaceList = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface iface in ifaceList)
    {
        if (iface.OperationalStatus == OperationalStatus.Up)
        {
            Console.WriteLine("Namett: " + iface.Name);
            Console.WriteLine("Typett: " + iface.NetworkInterfaceType);
            Console.WriteLine("Statustt: " + iface.OperationalStatus);
            Console.WriteLine("Speedtt: " + iface.Speed);
            Console.WriteLine("Descriptiont: " + iface.Description);

            UnicastIPAddressInformationCollection unicastIPC = iface.GetIPProperties().UnicastAddresses;
            foreach (UnicastIPAddressInformation unicast in unicastIPC)
            {
                Console.WriteLine(unicast.Address.AddressFamily + "t: " + unicast.Address);
            }
            Console.WriteLine("=======================================");
        }
    }
    Console.ReadKey();
}

One Thought on “Get All Local Network Interface Card (NIC) C# Source Code

  1. Andrés on April 4, 2016 at 6:10 pm said:

    Dear.

    I have the following code , the problem is that changing the IP email but email arrives with a wrong IP is sent , ones that have not changed. I could help with the issue , there is a way to take only changing a single network connection?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Net.NetworkInformation;
    using System.Net;
    using System.Net.Sockets;
    using System.Security.Principal;
    using System.Threading;
    using Microsoft.Win32;

    namespace InstaladorCambioIp
    {
    public partial class Service1 : ServiceBase
    {
    public static string ip = string.Empty;
    public static string usuario = string.Empty;
    public static string hostname = string.Empty;

    private const string Source = “MonitoreoIpUsuariosSource”;
    private const string Log = “MonitoreoIpUsuariosLog”;

    public string notificaAdministrator = “NO”;
    private static EventLog m_EventLog = new EventLog();

    public Service1()
    {
    InitializeComponent();
    ConfigureEventLog();
    notificaAdministrator = “NO”;
    }

    protected override void OnStart(string[] args)
    {
    notificaAdministrator = “NO”;

    try
    {
    ip = GetIP();
    }
    catch (Exception)
    {
    ip = string.Empty;
    }

    Thread thread = new Thread(new ThreadStart(EsUserAdministrador));
    thread.Start();

    m_EventLog.WriteEntry(“MonitoreoIpUsuarios iniciado”);

    try
    {
    usuario = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    }
    catch (Exception)
    {
    usuario = string.Empty;
    }

    try
    {
    hostname = GetHostName();
    }
    catch (Exception)
    {
    hostname = string.Empty;
    }

    NetworkChange.NetworkAddressChanged += new
    NetworkAddressChangedEventHandler(AddressChangedCallback);

    SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SysEventsCheck);

    base.OnStart(args);
    }

    public void SysEventsCheck(object sender, SessionSwitchEventArgs e)
    {
    switch (e.Reason)
    {
    case SessionSwitchReason.SessionLock:
    break;
    case SessionSwitchReason.SessionUnlock:
    break;

    case SessionSwitchReason.SessionLogoff:
    break;

    case SessionSwitchReason.SessionLogon:
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios escritor de evento SessionLogon…”);
    EsUserAdministrador();
    break;

    }
    }

    protected override void OnStop()
    {
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios deteniendo..”);
    bool esAdministrador;
    WindowsIdentity user = null;
    try
    {
    user = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(user);
    esAdministrador = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
    esAdministrador = false;
    }
    catch (Exception ex)
    {
    esAdministrador = false;
    }
    finally
    {
    if (user != null)
    user.Dispose();
    }

    if (esAdministrador)
    {
    base.CanStop = true;
    base.OnStop();
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios detenido servicio..”);
    }
    else
    {
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios no puede detener el servicio…”);
    base.CanStop = false;
    this.RequestAdditionalTime(1000);
    //throw new Exception();
    }
    }

    static void AddressChangedCallback(object sender, EventArgs e)
    {
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios cambio ip detectado…”);
    Mail m = new Mail();
    NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface n in adapters)
    {
    foreach (UnicastIPAddressInformation ipUnicast in n.GetIPProperties().UnicastAddresses)
    {
    if (ipUnicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
    try
    {
    if (ipUnicast.Address.ToString() != “127.0.0.1” && ip != “127.0.0.1” && ipUnicast.Address.ToString().Contains(“172.25”))
    {
    m_EventLog.WriteEntry(string.Format(“MonitoreoIpUsuarios Nueva ip: {0} Actual ip: {1}”, ipUnicast.Address.ToString(), ip));
    string error = string.Empty;

    m.EnviaMail(hostname, ip, ipUnicast.Address.ToString(), usuario, out error);

    if (!string.IsNullOrEmpty(error))
    {
    m_EventLog.WriteEntry(string.Format(“MonitoreoIpUsuarios error envio mail: {0} “, error));
    }
    }
    }
    catch (Exception ex)
    {
    m_EventLog.WriteEntry(string.Format(“MonitoreoIpUsuarios error en cambio ip: {0} “, ex.Message.ToString()));
    }
    }
    }
    }

    try
    {
    ip = GetIP();
    }
    catch (Exception)
    {
    ip = string.Empty;
    }
    }

    protected virtual void OnContinue()
    {
    m_EventLog.WriteEntry(“MonitoreoIpUsuarios escritor de evento OnContinue…”);
    }

    public static string GetIP()
    {
    string ipActual = string.Empty;
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
    ipActual = ip.ToString();
    }
    }
    return ipActual;
    }

    public static string GetHostName()
    {
    string host = string.Empty;
    host = Dns.GetHostName();
    return host;
    }

    private void ConfigureEventLog()
    {
    if (!EventLog.SourceExists(Source))
    {
    EventLog.CreateEventSource(Source, Log);
    }

    m_EventLog.Source = Source;
    m_EventLog.Log = Log;

    m_EventLog.WriteEntry(“MonitoreoIpUsuarios escritor de evento configurado…”);
    }

    public void EsUserAdministrador()
    {
    Mail m = new Mail();
    bool esAdministrador;
    WindowsIdentity user = null;
    try
    {
    user = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(user);
    esAdministrador = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
    esAdministrador = false;
    }
    catch (Exception ex)
    {
    esAdministrador = false;
    }
    finally
    {
    if (user != null)
    user.Dispose();
    }

    m_EventLog.WriteEntry(string.Format(“MonitoreoIpUsuarios usuario administador: {0}”, user.Name));

    if (notificaAdministrator == “NO”)
    {
    try
    {
    if (esAdministrador && (user.Name == “Administrator” || user.Name == “Administrador”))
    {
    string error = string.Empty;

    m.EnviaMail(ip, out error);
    if (!string.IsNullOrEmpty(error))
    {
    m_EventLog.WriteEntry(string.Format(“MonitoreoIpUsuarios error envio mail usuario administador: {0} “, error));
    }
    notificaAdministrator = “SI”;
    }
    }
    catch (Exception) { }
    }
    }
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation