简体   繁体   English

Android上的InetAddress.getByName

[英]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. 在我的Android应用程序中,但它永远不会解析主机名,它总是抛出异常,无论我使用什么名称。


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 到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;
}

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. 我遇到了类似的问题,我发现在某些版本的android(来自honeycombs)中,默认情况下不允许从主线程执行网络操作。 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);

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

It is strange that you have to do so. 你必须这样做很奇怪。 java.net.InetAddress.getByName works for me, out of the box. java.net.InetAddress.getByName适用于我,开箱即用。

There are some (on-going) issues related to DNS resolution in the Android emulator, so that might be it. Android模拟器中存在与DNS解析相关的一些(正在进行的)问题,因此可能就是这样。

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. 我试过getByName,它运行正常。

May be you fixed your permissions and switched from getByName to getAllByName at the same time? 可能是您修复了权限并同时从getByName切换到getAllByName? Just curious, if you can confirm that getByName still does not work for you? 只是好奇,如果你能确认getByName仍然不适合你吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM