ragz
ragz

Reputation: 99

Obtain IP address of wifi connected system

I am able to achieve Wi-fi communication between android and PC, by hard coding the IP address of the network connected. But i need to get the IP address of the system connected to a wi-fi network. Iam working on windows platform using C#. So please help me in this regard.

Upvotes: 1

Views: 8565

Answers (2)

Syaiful Nizam Yahya
Syaiful Nizam Yahya

Reputation: 4305

For UWP, use this to get your local Ip Address. Updated based on answers by @L.B.

var addresses = Dns.GetHostEntryAsync((Dns.GetHostName()))
                .Result
                .AddressList
                .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
                .Select(x => x.ToString())
                .ToArray();

Upvotes: 1

DIXONJWDD
DIXONJWDD

Reputation: 1286

This may work for you:

string[] strIP = null;
int count = 0;

IPHostEntry HostEntry = Dns.GetHostEntry((Dns.GetHostName()));
if (HostEntry.AddressList.Length > 0)
{
    strIP = new string[HostEntry.AddressList.Length];
    foreach (IPAddress ip in HostEntry.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            strIP[count] = ip.ToString();
            count++;
        }
    }
}

The problem is, the host could have many IP addresses. This is why the string array is used, it collects them all.

--EDITED by L.B--

Here is the the working version of the code above

var addresses = Dns.GetHostEntry((Dns.GetHostName()))
                    .AddressList
                    .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
                    .Select(x => x.ToString())
                    .ToArray();

Upvotes: 4

Related Questions