Android获取WIFI下的IP地址以及MAC地址

代码片段一:

WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);WifiInfo info = wifiMan.getConnectionInfo();String mac = info.getMacAddress();// 获得本机的MAC地址String ssid = info.getSSID();// 获得本机所链接的WIFI名称int ipAddress = info.getIpAddress();String ipString = "";// 本机在WIFI状态下路由分配给的IP地址// 获得IP地址的方法一:if (ipAddress != 0) {       ipString = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));}// 获得IP地址的方法二(反射的方法):try {Field field = info.getClass().getDeclaredField("mIpAddress");field.setAccessible(true);ipString = (String) field.get(info);System.out.println("obj" + ipString);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}

代码片段二:

 package android.net.wifi; import android.net.NetworkUtils;  public int getIpAddress() {        if (mIpAddress == null || mIpAddress instanceof Inet6Address) return 0;        return NetworkUtils.inetAddressToInt(mIpAddress);    }

代码片段三:

 package android.net; public class NetworkUtils {/***     * Convert a IPv4 address from an InetAddress to an integer     * @param inetAddr is an InetAddress corresponding to the IPv4 address     * @return the IP address as an integer in network byte order     */    public static int inetAddressToInt(InetAddress inetAddr)            throws IllegalArgumentException {        byte [] addr = inetAddr.getAddress();        if (addr.length != 4) {            throw new IllegalArgumentException("Not an IPv4 address");        }        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |                ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);        } } 

代码片段四:

package android.net.wifi;

/** * Copy constructor * @hide */ public WifiInfo(WifiInfo source) { if (source != null) { mSupplicantState = source.mSupplicantState; mBSSID = source.mBSSID; mSSID = source.mSSID; mNetworkId = source.mNetworkId; mHiddenSSID = source.mHiddenSSID; mRssi = source.mRssi; mLinkSpeed = source.mLinkSpeed; mIpAddress = source.mIpAddress; mMacAddress = source.mMacAddress; mMeteredHint = source.mMeteredHint; } }



   

更多相关文章

  1. android典型代码系列(三十)------DES加密算法
  2. 使用 Android NDK 重用现有的 C 代码
  3. 修改Android的开关机铃声、Android开关机画面与动画(附代码流程)
  4. Android 初学入门代码注释 学习笔记001 16.03.18

随机推荐

  1. Android(安卓)Bluetooth蓝牙技术基础讲解
  2. dex.force.jumbo和Java heap space的问题
  3. android 为摄像头增加闪光灯(s5pv210)
  4. Android获取网速和下载速度
  5. Caused by: java.lang.ClassNotFoundExce
  6. 对于Android的一些牢骚
  7. Android个人所得税计算器
  8. Android开发者,是时候了解LeakCanary了
  9. 在Android中解析ls 命令得到目录列表的方
  10. android 录音和播放