InetAddress.getByName on Android

前端 未结 4 1764
别跟我提以往
别跟我提以往 2020-12-11 17:53

I do a:

java.net.InetAddress serverAddr;
try {
    serverAddr = java.net.InetAddress.getByName(Server.SERVERNAME);
}
catch (java.net.UnknownHostException exc         


        
相关标签:
4条回答
  • 2020-12-11 18:05

    I was having the similar issue and I found out that in some versions of android (from honeycombs) it's not allowed by default to perform network operation from main thread. So you can resolve it in 2 ways. Perform operation in different thread or allow to make network operation in main thread. To do that use something like this:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
    StrictMode.setThreadPolicy(policy);
    
    0 讨论(0)
  • 2020-12-11 18:06

    Don't know if it was a typo, but you said you have:

    <use-permission id="android.permission.INTERNET" />
    

    But it have to be:

    <uses-permission android:name="android.permission.INTERNET" />
    

    I tried getByName and it works fine.

    May be you fixed your permissions and switched from getByName to getAllByName at the same time? Just curious, if you can confirm that getByName still does not work for you?

    0 讨论(0)
  • 2020-12-11 18:21

    I've found the answer. For whatever reason, you have to use:

    java.net.InetAddress[] x= java.net.InetAddress.getAllByName(Server.SERVERNAME) ; HelloWorldActivity.tv.setText("Address: "+x[0].getHostAddress());

    0 讨论(0)
  • 2020-12-11 18:21

    It is strange that you have to do so. java.net.InetAddress.getByName works for me, out of the box.

    There are some (on-going) issues related to DNS resolution in the Android emulator, so that might be it.

    0 讨论(0)
提交回复
热议问题