简体   繁体   English

获取本地IP地址

[英]Getting local IP address

I'm trying to get the local IP address of my Android device using Mono for Android, but failing.我正在尝试使用 Mono 为 Android 获取我的 Android 设备的本地 IP 地址,但失败了。

The code I use for the full and compact framework is this:我用于完整和紧凑框架的代码是这样的:

var iplist = (from a in Dns.GetHostAddresses(Dns.GetHostName())
              where a.AddressFamily == AddressFamily.InterNetwork
              select a).ToArray();
LocalAddress = iplist[0];

Under M4A, however, it falls down early - the Dns.GetHostName() call fails with但是,在 M4A 下,它会提前下降 - Dns.GetHostName() 调用失败并显示

System.Net.Sockets.SocketException: An address incompatible with the requested protocol was used

Is there a known issue with Dns.GetHostName under M4A? M4A 下的 Dns.GetHostName 是否存在已知问题? Is there an alternate way to get the local address using M4A?有没有其他方法可以使用 M4A 获取本地地址?

It turns out that this is an exception thrown in the internals of the Mono Socket implementation, related to the runtime trying to determine if IPv6 is supported ( source here , line 810 as of this writing).事实证明,这是 Mono Socket 实现内部抛出的异常,与尝试确定是否支持 IPv6 的运行时相关( 来源此处,撰写本文时的第 810 行)。

The exception is thrown the first time you attempt to use any Socket under Mono and can be safely ignored.第一次尝试使用 Mono 下的任何 Socket 时会抛出异常,可以安全地忽略它。 If you're running with your debugger to "Break on all thrown exceptions", which I occasionally do to ensure code cleanliness, you'll have to specifically turn off SocketExceptions or just Continue past this break.如果您使用调试器运行以“中断所有抛出的异常”(我偶尔会这样做以确保代码清洁),则您必须专门关闭 SocketExceptions 或仅继续此中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM