How can you get the ip of the device in C#? That it works in the scope of the UWP (Universal Windows Platform) known as universal applications of windows10
You should ask for the internet connection profile, then check which is the current network adapter that matches the profile.
Keep in mind that you have to validate many things, such as whether or not devices exist, or if more than one exists. The device may even exist but you are not connected to a network. Etc.
Use this method to find the local IP that already has everything implemented.
private string GetLocalIp()
{
var icp = NetworkInformation.GetInternetConnectionProfile();
//sino hay disp de red devuelve null
if (icp?.NetworkAdapter == null) return null;
var hostname = (from hn in NetworkInformation.GetHostNames()
where hn.IPInformation?.NetworkAdapter != null
&& hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId
select hn).First();
return hostname?.CanonicalName;
}
With this other method (below) you can find the address with which it goes out to the internet, which is not the same local IP. NetworkInformation.GetHostNames()returns a list of interfaces some with IP, in any case the order of these interfaces is .
IP
Interfaces without IP
Interfaces with IP
network type
external
local
so this method returns with the first interface with external IP.
private string GetIp()
{
string ip = string.Empty;
var ll = NetworkInformation.GetHostNames().ToList();
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
ip = localHostName.ToString();
break;
}
}
}
return ip;
}
You should ask for the internet connection profile, then check which is the current network adapter that matches the profile.
Keep in mind that you have to validate many things, such as whether or not devices exist, or if more than one exists. The device may even exist but you are not connected to a network. Etc.
Use this method to find the local IP that already has everything implemented.
With this other method (below) you can find the address with which it goes out to the internet, which is not the same local IP.
NetworkInformation.GetHostNames()
returns a list of interfaces some with IP, in any case the order of these interfaces is .so this method returns with the first interface with external IP.
Here you can look at API documentation: Windows.Networking
Try this code: