How to get the computer's ip address into a variable?

  • one
    Which one 127.0.0.1 would work? - Alexey Ten
  • and you know that these ip from kompyuet dofiga? If you have ezernet and wifi, then there are already 2. If the virtual network is still configured one more. If the proxy is also one more. And one piece of iron can have versions 4 and 6 ... at the same time ... What is it? - Andrew
  • Well, actually the virtual network raised by the router, the connection is wired) - Keeplod
  • one
    Well, then only one option, first do a sampling of network cards by the adapter name, and then on the selected adapter get an IP address. To see a full selection of your network, enter ipconfig /all into the console. And yes, this is not a virtual network already ('a virtual network raised by a router') if it is raised by a router, then this network is quite real. The answer proapdetyl. - Andrew

1 answer 1

The solution will not work on any machine:

 public static string GetLocalIPAddress() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } throw new Exception("No network adapters with an IPv4 address in the system!"); } 

it may return an incorrect result if there are virtual network cards or several physical ones.


upd:

 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (var adapter in interfaces) { // здесь ищешь адаптер по нужным параметрам // и здесь же достаешь айпишник } 
  • DNS may not be configured at all, unavailable or blocked ... - Akina
  • @Akina totally, absolutely and irrevocably agree) What is the ̶s̶t̶o̶l̶ ̶t̶a̶k̶o̶y̶ ̶ and̶ ̶s̶t̶ul̶ question and the answer. - Andrew