0

Is there a reliable way to get the IPv4 address of the first local Ethernet interface in C#?

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
    {...

This finds the local IP address associated with the Ethernet adapter but also find the Npcap Loopback Adapter (installed for use with Wireshark).

Similarly, there seems to be no way to tell the difference between the loopback address and the Ethernet address using the following code:

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{....

Any other suggestions?

Matt Davis
  • 45,297
  • 16
  • 93
  • 124
Adrian S
  • 514
  • 7
  • 16
  • This explains how to get the address of the hostname for the machine. http://stackoverflow.com/questions/9855230/how-do-i-get-the-network-interface-and-its-right-ipv4-address (which might be more important than which is "first" adapter) – ebyrob Jun 22 '16 at 20:28
  • That doesn't help. It gives both addresses (the Ethernet card address and the Npcap loopback address). – Adrian S Jun 22 '16 at 20:32

1 Answers1

3

The following code gets the IPv4 from the preferred interface. This should also work inside virtual machines.

using System.Net;
using System.Net.Sockets;

public static void getIPv4()
    {
        try
        {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("10.0.1.20", 1337); // doesnt matter what it connects to
                IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                Console.WriteLine(endPoint.Address.ToString()); //ipv4
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Failed"); // If no connection is found
        }
    }
Snazzie
  • 197
  • 1
  • 3
  • 12
  • Thanks - this does work perfectly but could you explain why? – Adrian S Jun 22 '16 at 21:48
  • " Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,0)) " its making a connection-less UDP connection which will contain your outbound IP address. then you would get the outbound IP from it. – Snazzie Jun 22 '16 at 22:18