Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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's never resoling the hostname, it always throws an exception, no matter what name I use.


But using the internet on the same emulator works, and I've added

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

to AndoidManifest.xml

and here's the server class for those who assume I have none

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;
}
like image 624
Stefan Steiger Avatar asked Jan 19 '10 20:01

Stefan Steiger


2 Answers

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);
like image 127
Reg Edit Avatar answered Sep 21 '22 09:09

Reg Edit


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());

like image 25
Stefan Steiger Avatar answered Sep 20 '22 09:09

Stefan Steiger