我试过这段代码 公共类MainActivity扩展了Activity {
private static final String TAG = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv= (TextView) findViewById(R.id.textView2);
String a=getLocalIpAddress();
tv.setText(a);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String a= inetAddress.getHostAddress();
return a;
}
}
}
} catch (SocketException ex) {
// Log.e(tag, ex.toString());
}
return "";
}
}
这给了我像00ff这样的ip地址:22ff:.... 但我希望它像192.168.3.3 ... 格式ip地址已折旧 有没有其他方法,以便我可以获得格式化地址
答案 0 :(得分:-1)
您获得的地址是IPv6。你想要得到的是IPv4,所以尝试使用:
if ((!inetAddress.isLoopbackAddress()) && (InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress()))) { ... }
而不是:
if (!inetAddress.isLoopbackAddress()) { ... }