InetAddress.getByName on Android

I do a:

java.net.InetAddress serverAddr;
try {
    serverAddr = java.net.InetAddress.getByName(Server.SERVERNAME);
}
catch (java.net.UnknownHostException exception) {
    //System.err.println ("wrong server name !!!");
    HelloWorldActivity.tv.setText("wrong server name !!!");
    return;
}

in my Android application, but it never resolves the host name, it always throws an exception, no matter what name I use.


But using the Internet on the same emulator works, and I added

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

in AndoidManifest.xml

and here is the server class for those who suggested that I don't have

public class Server
{
    public static String SERVERNAME = "monster.idsoftware.com";
    public static String SERVERIP = "209.85.129.99";
    public static int SERVERPORT = 27950;
    public static int PROTOCOL = 68;
}
+5
source share
4 answers

I have found the answer. For some reason you should use:

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

+4
source

It is strange that you have to do this. java.net.InetAddress.getByNameworks for me out of the box.

There are some (current) issues related to DNS resolution in the Android emulator, so that may be.

+1
source

, , android ( ) . , . . - :

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
+1

, , , :

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

:

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

getByName, .

Perhaps you fixed your permissions and switched from getByName to getAllByName at the same time? Curious if you can confirm that getByName still doesn't work for you?

0
source

All Articles