Get local IP address of ethernet interface in C#

后端 未结 1 1887
眼角桃花
眼角桃花 2021-01-29 00:49

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

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInter         


        
相关标签:
1条回答
  • 2021-01-29 01:17

    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
            }
        }
    
    0 讨论(0)
提交回复
热议问题