我正在开发一个 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/