Obtain Local Network Interface using C#

As a developer, sometimes you need to obtain about the network adapters and network config of your local machine..... so i created a simple code snippets that might help somebody!!!


for simplicity I only checked for Ethernet interface only.... so let's check it out


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;

namespace LanInterface
{
    class Program
    {
        static void Main(string[] args)
        {

            // as shown above we used System.Net.NetworkInformation namespace so could use some of its classes

            //lets check for network availability
            bool bolNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();

            try
            {
                if (bolNetworkAvailable)
                {

                    //lets get all of the Network Interface for the current machine

                    NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

                    foreach (NetworkInterface ints in interfaces)
                    {
                        // lets output to the screen some of the basic information!

                        //lets only focus on Ethernet type only for simplicity
                        if (ints.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                        {

                            Console.WriteLine("Network ID: {0}", ints.Id);
                            Console.WriteLine("Network Name: {0}", ints.Name);
                            Console.WriteLine("Network Type: {0}", ints.NetworkInterfaceType);
                            Console.WriteLine("Network Description: {0}", ints.Description);
                            Console.WriteLine("Network Status: {0}", ints.OperationalStatus);
                            Console.WriteLine("Network Speed: {0}", ints.Speed);

                            //lets get the physical address

                            Console.WriteLine("Network MAC Address {0}", ints.GetPhysicalAddress().ToString());
                           
                            //lets get the network statistics

                            Console.WriteLine("Bytes Send: {0}", ints.GetIPv4Statistics().BytesSent);
                            Console.WriteLine("Bytes Received: {0}", ints.GetIPv4Statistics().BytesReceived);


                            Console.WriteLine("\r\n");

                        }
                    }
                }
                else
                {
                    Console.WriteLine("NIC or LAN not available");
                }
            }
            catch (NetworkInformationException ex)
            {
                Console.WriteLine(ex.Message);
            }
           
            Console.ReadLine();
        }
    }
}

0 comments:

Post a Comment