Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting local IP address

I'm trying to get the local IP address of my Android device using Mono for Android, but failing.

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

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

Is there a known issue with Dns.GetHostName under M4A? Is there an alternate way to get the local address using M4A?

like image 924
ctacke Avatar asked Apr 06 '12 16:04

ctacke


1 Answers

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).

The exception is thrown the first time you attempt to use any Socket under Mono and can be safely ignored. 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.

like image 104
ctacke Avatar answered Oct 11 '22 12:10

ctacke