Get local IP address

前端 未结 26 2607
野的像风
野的像风 2020-11-22 10:07

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

String strHostName = string.Empty;         


        
26条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 10:53

    There is a more accurate way when there are multi ip addresses available on local machine. Connect a UDP socket and read its local endpoint:

    string localIP;
    using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
    {
        socket.Connect("8.8.8.8", 65530);
        IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
        localIP = endPoint.Address.ToString();
    }
    

    Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.

    So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.

提交回复
热议问题