一聚教程网:一个值得你收藏的教程网站

热门教程

Android获取手机ip程序代码

时间:2022-11-14 22:17:39 编辑:袖梨 来源:一聚教程网

实例

代码如下 复制代码

public String getLocalIpAddress() {
try {
for (Enumeration en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("ifo", ex.toString());
}
return "";
}

public String getLocalMacAddress(Context context) {
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}

安卓4.0系统的手机,按上面的方法默认会先获取到ipv6的地址,有时候我们只想要ipv4的地址

代码如下 复制代码
/**
* 用来获取手机拨号上网(包括CTWAP和CTNET)时由PDSN分配给手机终端的源IP地址。
*
* @return
* @author SHANHY
*/
public static String getPsdnIp() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
//if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception e) {
}
return "";
}

热门栏目