Friday, July 12, 2013

WPF - Different ways to get System IP Address

Following method get the local from the list of Addresses as it has more IP address if it has more adapters

private object GetLocalIPAddressFromAddressList()
        {
            var hostName = Dns.GetHostName();
            var ipEntry = Dns.GetHostEntry(hostName);

            var result = from address in ipEntry.AddressList
                    where address.AddressFamily == AddressFamily.InterNetwork
                    select address;
            return result.LastOrDefault();

        }


Using Ping method to get the IP Address, it helpful to find others IP address also

        public IPAddress GetIPAddressUsingPing()
        {
            string hostName = "rbalajiprasad.blogspot.com";
            //You can get local Computer IP address also by sending HostName by following
            //string hostName = System.Net.Dns.GetHostName();


            Ping ping = new Ping();
            var replay = ping.Send(hostName);

            if (replay.Status == IPStatus.Success)
            {
                return replay.Address;
            }
            return null;
        }