2

I am looking for method which identifies if the system is connected to the network or gets the local ip address when virtual machines are install on the system. This is the code which returns the local ip address:

 public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

But when the system is not connected to the network it returns the other VM ip address.
I also found this method System.Net.NetworkInformation.NetworkInterface.isconnected method available but it returns true even when the network cable is unplugged.
Is there any way to find out if the system is connected or not?

leppie
  • 115,091
  • 17
  • 196
  • 297
Mulesoft Developer
  • 2,664
  • 5
  • 28
  • 41

4 Answers4

2

The following line will do get your local IP address

string ipadress = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)
.ToString();
Dinesh Kumar P
  • 1,128
  • 2
  • 18
  • 32
2

Try this:

using System.Net;

private string GetIP()
{
    string strHostName = System.Net.Dns.GetHostName();
    IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
    IPAddress[] addr = ipEntry.AddressList;
    return addr[addr.Length-1].ToString();
}
Jeff B
  • 8,572
  • 17
  • 61
  • 140
JayOnDotNet
  • 398
  • 1
  • 5
  • 17
  • 1
    This code worked, but I had to change `addr[addr.Length-1]` to `addr[0]`. It'd probably be better match the first address that's `AddressFamily.InterNetwork` like one of the other answers does below. – Jeff B Sep 28 '18 at 13:10
0
Try This:

      using System;
      using System.Net;
      namespace GetLocalIP
       {
        class Program
         {
          static void Main(string[] args)
            {
             string host = Dns.GetHostName();
             string AddressIP6 = string.Empty;
             IPAddress[] IPAdd = Dns.GetHostAddresses(host);
             foreach (IPAddress ip6 in IPAdd){
             AddressIP6 = ip6.ToString();
            }
          Console.WriteLine("Local system IP Address : " + AddressIP6);
        Console.ReadKey();
      }
    }
 }
Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
0

http://www.csharp-examples.net/local-ip/

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171