Xamarin INetAddress.GetByName always throws exception

744 views Asked by At

I'm trying to get the INetAddress with the following code:

try
{
  var address = InetAddress.GetByName ("google.com");
  System.Diagnostics.Debug.WriteLine (address);
}
catch (Java.Net.UnknownHostException)
{
  System.Diagnostics.Debug.WriteLine ("not working");
}

But it always prints "not working". I checked and my internet connection is fine. I don't know why this is happening. Thank's in advance.

1

There are 1 answers

0
Dmitry Zinoviev On

I could solve this by using AsyncTask.

here is my implementation

    public class ConnectionCheckAsyncTask : AsyncTask
    {
        private bool isInternetReachable()
        {
            try
            {
                var address = InetAddress.GetByName("google.com");
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        protected override Object DoInBackground(params Object[] @params)
        {
            var res = isInternetReachable();
            return res;
        }
    }

to get result you need to do next

    var task = new ConnectionCheckAsyncTask();
    task.Execute();
    var isReacheble = (bool)await task.GetAsync();

One more option to check inet connection. All you need is change isInternetReachable in ConnectionCheckAsyncTask with next code

        private bool isInternetReachable()
        {
            try
            {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlConnect = (HttpURLConnection)url.OpenConnection();
                Object objData = urlConnect.GetContent(new Class[0]);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }