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 block
e.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 SDK更新以及ADT更新出现问题的解决办法(附google服务器
  2. javaScript函数中执行C#代码中的函数
  3. 反编译APK 得到JAVA代码和资源文件源码
  4. java.io.File vs java.nio.Files这是新代码中的首选?
  5. 拖动层的javasvript代码 十行代码即可写出兼容版拖动层
  6. 我无法让这个简单的ajax代码工作
  7. javascript实现拖动层效果代码(许愿墙)
  8. 牛客网Java刷题知识点之同步方法和同步代码块的区别(用synchroniz
  9. 在java自动生成hashCode代码问题? 请大神赐教

随机推荐

  1. 坚持写作快两年了,有些私藏工具跟你们分享
  2. 【同说】机械转行前端,半年零基础自学的心
  3. RocketMQ 源码分析 —— Message 存储
  4. RocketMQ 源码分析 —— 高可用
  5. Guava Cache本地缓存在 Spring Boot应用
  6. RocketMQ 源码分析 —— Filtersrv
  7. Android(安卓)TV横向滚动网格布局——Rec
  8. RocketMQ 源码分析 —— 定时消息与消息
  9. 芋道 Spring Boot 对象转换 MapStruct 入
  10. 每天都在用 Map,这些核心技术你知道吗?