How do I get the Local Network IP address of a computer programmatically?

后端 未结 5 849
萌比男神i
萌比男神i 2020-11-28 06:10

I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can\'t just use 127.0.0.1 in this case.

<
5条回答
  •  孤城傲影
    2020-11-28 06:40

    If you know there are one or more IPv4 addresses for your computer, this will provide one of them:

    Dns.GetHostAddresses(Dns.GetHostName())
        .First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()
    

    GetHostAddresses normally blocks the calling thread while it queries the DNS server, and throws a SocketException if the query fails. I don't know whether it skips the network call when looking up your own host name.

提交回复
热议问题