java - 为什么InetAddress.getLocalHost().getHostAddress()在android中返回127.0.0.1。但在JAVA程序中工作正常

标签 java android

我正在开发一个 Android 应用程序,它可以返回连接到 WI-FI 网络的设备的 IP 地址。当我使用代码时

InetAddress.getLocalHost().getHostAddress();

在JAVA程序中,它返回我的IP为10.160.2.197(这正是我想要的)。但是当我在 Android 应用程序中运行此代码时,它返回 127.0.0.1 该设备已连接到 WIFI。
Stackoverflow中的一些解决方案建议使用

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

是否无法使用InetAddress.getLocalHost().getHostAddress();获取IP地址
如果不是那么为什么?

Here is my code

 public class MainActivity extends Activity {

     private Button b;
     private TextView t;

     @Override
     protected void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         b=(Button)findViewById(R.id.button);
         t=(TextView)findViewById(R.id.ip);
         b.setOnClickListener(new View.OnClickListener() {

           @Override
           public void onClick(View arg0) {
              getIp obj=new getIp();
              obj.execute()
           }
        });   
     }    

    class getIp extends AsyncTask<Void,Integer,Void>
    {

        String ip;

        public Void doInBackground(Void...params)
        {
             try {
                  ip=InetAddress.getLocalHost().getHostAddress();
                 } catch (UnknownHostException e) {
                 // TODO Auto-generated catch block
                   e.printStackTrace();
                 }
              return null;
        }

        public void onPostExecute(Void result){
            t.setText(ip);
        }


     }
 }

Manifest contains following permissions

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

最佳答案

这是 Android 上的预期行为。请参阅 javadoc getLocalHost() :

Note that if the host doesn't have a hostname set – as Android devices typically don't – this method will effectively return the loopback address, albeit by getting the name localhost and then doing a lookup to translate that to 127.0.0.1.

关于java - 为什么InetAddress.getLocalHost().getHostAddress()在android中返回127.0.0.1。但在JAVA程序中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385173/

相关文章:

java - 如何使用 Spring 轻松使用 JSP 页面作为电子邮件模板?

c# - 在 Xamarin Android 中存储 SQLite 数据库的路径

android - 将OpenCV中的Mat从MLkit中传递给Facedetector

android - Flutter - 如何使用 Firebase 获得动态主页?

android - 隐藏由 Theme.AppCompat.Light.NoActionBar 引起的 FloatingMenu

java - 在 BlackBerry 上通过短信、电子邮件、推特、Facebook 分享

java - 用 Java 改变我的 Android 应用的整体风格

java - 如何使用反射自动注册spring bean

java - 如何调试外部 JAR 文件

android - android中的两个应用程序可以使用本地套接字进行通信吗?