Pegar o IP local ignorando máquinas virtuais

<< Click to Display Table of Contents >>

Navigation:  Rede e Internet >

Pegar o IP local ignorando máquinas virtuais

Previous pageReturn to chapter overviewNext page

public static string GetIPAddress()

{

  string returnAddress = String.Empty;

   

   // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)

   NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

   

   foreach (NetworkInterface network in networkInterfaces)

   {

      // Read the IP configuration for each network

       IPInterfaceProperties properties = network.GetIPProperties();

      if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet && network.OperationalStatus == OperationalStatus.Up &&

           !network.Description.ToLower().Contains("virtual") && !network.Description.ToLower().Contains("pseudo"))

       {

          // Each network interface may have multiple IP addresses

          foreach (IPAddressInformation address in properties.UnicastAddresses)

           {

              // We're only interested in IPv4 addresses for now

              if (address.Address.AddressFamily != AddressFamily.InterNetwork)

                  continue;

 

              // Ignore loopback addresses (e.g., 127.0.0.1)

              if (IPAddress.IsLoopback(address.Address))

                  continue;

               

               returnAddress = address.Address.ToString();

              // Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");

           }

       }

   }

  return returnAddress;

}