Search code examples
c#ipvirtual-machinelan

Get IP of my machine C# with virtual machine installed


I want to get the current IP address of the computer that has say 3 virtual machines (VM Ware) installed. I want to get LAN address of that computer.

current code that i have returns me an array but how to identify current computer lan address ?

public static string getThisCompIPAddress()
    {
        IPAddress[] addresslist = Dns.GetHostAddresses(Dns.GetHostName());
        return (addresslist[0].ToString());


    }

addresslist returns an array of 3 IP addresses


Solution

  • public static ArrayList getThisCompIPAddress()
        {
            ArrayList strArrIpAdrs = new ArrayList();
            ArrayList srtIPAdrsToReturn = new ArrayList();
            addresslist = Dns.GetHostAddresses(Dns.GetHostName());
            for (int i = 0; i < addresslist.Length; i++)
            {
                try
                {
                    long ip = addresslist[i].Address;
                    strArrIpAdrs.Add(addresslist[i]);
                }
                catch (Exception ex) 
                {
                    Console.WriteLine(ex.Message);
                }
    
            }
    
            foreach (IPAddress ipad in strArrIpAdrs)
            {
    
                lastIndexOfDot = ipad.ToString().LastIndexOf('.');
                substring = ipad.ToString().Substring(0, ++lastIndexOfDot);
                if (!(srtIPAdrsToReturn.Contains(substring)) && !(substring.Equals("")))
                {
                    srtIPAdrsToReturn.Add(substring);
                }
            }
    
            return srtIPAdrsToReturn;
        }
    

    this is 100% working, the real problem was that it was throwing error while calculating Address that returns long. Error Code is 10045