1.获取局域网ip和mac(如果电脑没有直接连接外网),否则获取公网ip
2.通过第三放获取公网ip
public class NetworkUtils {
/**
* 获取本地IP列表(针对多网卡情况)
* @return
*/
public static Map<String, Object> getLocalInetMac() {
Map<String, Object> ipMacInfo = null;
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces
.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface
.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
ipMacInfo = pickInetAddress(inetAddress, networkInterface);
if (ipMacInfo != null) {
Log.e("IP-MAC-1",ipMacInfo );
return ipMacInfo;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
private static Map<String, Object> pickInetAddress(InetAddress inetAddress,
NetworkInterface ni) {
try {
String name = ni.getDisplayName();
if (name.contains("Adapter")
|| name.contains("Virtual") || name.contains("VMnet") || name.contains("#")) {
return null;
}
if (ni.isVirtual() || !ni.isUp() || !ni.supportsMulticast()) {
return null;
}
if (inetAddress.isSiteLocalAddress()) {
Formatter formatter = new Formatter();
String sMAC = null;
byte[] macBuf = ni.getHardwareAddress();
for (int i = 0; i < macBuf.length; i++) {
sMAC = formatter.format(Locale.getDefault(), "%02X%s",
macBuf[i], (i < macBuf.length - 1) ? "-" : "")
.toString();
}
formatter.close();
Map<String, Object> ipMacInfo = new HashMap<String, Object>();
ipMacInfo.put("hostname", inetAddress.getHostName()); //系统当前hostname
ipMacInfo.put("ip", inetAddress.getHostAddress()); //ip地址
ipMacInfo.put("ipnet&#