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

时间:2016-02-13 20:50:24

标签: java android

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

glBufferData(GL_ARRAY_BUFFER, n * sizeof(GLfloat), complex_values_array, GL_DYNAMIC_DRAW);

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

127.0.0.1

是否无法使用WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress()); 获取IP地址 如果没有那么为什么?

  

这是我的代码

InetAddress.getLocalHost().getHostAddress();
  

Manifest包含以下权限

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


     }
 }

2 个答案:

答案 0 :(得分:1)

如果您拥有ACCESS_WIFI_STATE的权限,这应该适合您。

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

答案 1 :(得分:1)

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

  

请注意,如果主机没有设置主机名 - 作为Android设备   通常不会 - 这种方法将有效地返回环回   地址,虽然通过获取名称localhost然后进行查找   把它翻译成127.0.0.1。