英文:
How to get Local Router Address[Not IPV4 address of device] in Xamarin
问题
我已尝试下面的代码,但它一直给我iPhone(即设备) IP地址。但我想要获取路由器IP地址。
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(netInterface);
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
{
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = addrInfo.Address.ToString();
}
}
}
}
}
> iPhone IP地址: 192.168.0.19
> 路由器: 192.168.0.1
我可以采取从IP地址的最后一组中删除'9'的方法,但我不想这样做。
英文:
I have tried below code but it keeps on giving the me iPhone(ie.Device) IP Address. But I want to get a ROUTER IP ADDRESS
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(netInterface);
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
{
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = addrInfo.Address.ToString();
}
}
}
}
> iPhone IPAddress: 192.168.0.19
> Router: 192.168.0.1
I can do the Hacky way of removing the '9' from the last set of IP address. But I don't want to do this.
答案1
得分: 1
您可以使用以下代码从Android侧获取路由器IP地址(网关地址)。
在Forms文件夹中创建一个DependenceService
。
然后在Android文件夹中实现此接口。
在AndroidManifest.xml中添加以下权限。
在Xamarin Forms中,您可以像以下代码一样获取路由器IP地址。
英文:
You can use the following code to get a ROUTER IP ADDRESS(Gateway address) from Android side.
Create a DependenceService in Forms folder.
public interface INetServices
{
string ConvertGateway();
}
Then achieve this interface in the android folder.
[assembly: Dependency(typeof(NetService))]
namespace Forms.Droid
{
class NetService: INetServices
{
[Obsolete]
public string ConvertGateway()
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);
int ip = wifiManager.ConnectionInfo.IpAddress;
int gateway = wifiManager.DhcpInfo.Gateway;
IPAddress ipAddr = new IPAddress(ip);
IPAddress gatewayAddr = new IPAddress(gateway);
return gatewayAddr.ToString();
}
}
}
And add following permission in the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
In the Xamarin forms, you can get ROUTER IP ADDRESS like following code.
var gatewayAddress = DependencyService.Get<INetServices>().ConvertGateway();            
Console.WriteLine(gatewayAddress);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论