在清单文件中加入以下权限AndroidManifest.xml:
引用
<!-- 访问网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 访问Wi-Fi网络 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
获取Android本机IP地址和MAC,Test.java类:
package com.iaiai.test;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import android.content.Context;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.test.AndroidTestCase;import android.util.Log;public class Test extends AndroidTestCase { private final String TAG = "Test"; public void testLocalIpAndMac() { Log.i(TAG, "IP: " + getLocalIpAddress() + ", MAC: " + getLocalMacAddress()); } /** * 获取Android本机IP地址 * * @return */ private 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()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("WifiPreference IpAddress", ex.toString()); } return null; } /** * 获取Android本机MAC * * @return */ private String getLocalMacAddress() { WifiManager wifi = (WifiManager) this.getContext().getSystemService( Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); return info.getMacAddress(); }}
运行结果: