How to get the IP address of the server on which my C# application is running on?

前端 未结 26 1969
天命终不由人
天命终不由人 2020-11-22 06:01

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer\'s own (if possible, external) IP address?

Someon

26条回答
  •  [愿得一人]
    2020-11-22 06:34

    return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
    

    Simple single line of code that returns the first internal IPV4 address or null if there are none. Added as a comment above, but may be useful to someone (some solutions above will return multiple addresses that need further filtering).

    It's also easy to return loopback instead of null I guess with:

    return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) ?? new IPAddress( new byte[] {127, 0, 0, 1} );
    

提交回复
热议问题