你好我使用下面的代码获取android设备的IP地址,
private String returnIPAdrress()
{
String IPAddress = null;
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())
{
IPAddress = inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException ex)
{
Log.e("ServerActivity", ex.toString());
return null;
}
return IPAddress;
}
当我在Galaxy平板电脑上测试它(os = 2.3)时,它工作正常,并为我提供有效的IP地址。
我在模拟器上测试了它(os = 2.2),它给我的IP地址为 10.0.2.15 ,这也是有效的。
但是当它在Micromax canvas(os = 4.1)上运行时,它给我的IP地址为 fe80 :: d0b3:3fff:fe9d:f68c%p2p0 这是错误的
是因为OS版本不同吗?
我该如何解决这个问题?
答案 0 :(得分:3)
试试这个方法:
public static String getIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4 && intf.getDisplayName().startsWith("wlan")) {
return sAddr;
}
}
}
}
} catch (Exception ex) {
return null;
}
return null;
}
答案 1 :(得分:1)
您可以使用dhcp.ipaddress
private final WifiManager manager;
private final DhcpInfo dhcp;
private InetAddress getMyIP() {
manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.ipAddress); // ipAddress - IP address of my device, assigned through dhcp
InetAddress myIP = null;
try {
myIP = InetAddress.getByName(address);
Log.i("My IP "," + myIP.toString());
} catch (Exception e) {
Log.e("Cannot find my own IP. Error ", e.toString());
}
return myIP;
}