关于IP
1.IP 网际协议地址(Internet Protocol Address)
2.是TCP/IP协议族中网络层的协议
3.互联网上的每一个网络和每一台主机分配一个逻辑地址,以此来屏蔽物理地址的差异
IPv4
1.IP协议第四版
2.位数为32位,即32个0,1排列组合形成的不同数值,每个数值可对应Internet的一个逻辑地址,共2的32次方个。
3.每个逻辑地址可供一个设备连接到Internet,通过这个逻辑地址就能寻找到某个设备。
获取手机的IPv4
仅开启移动数据时:
{ccmni0=10.66.253.0,
lo=127.0.0.1}
开启手机热点时:
{ccmni0=10.66.253.0,
lo=127.0.0.1,
ap0=192.168.43.1}
连上WLAN(无线时):
{Mac=1c:77:f6:11:1e:4e,
name="FAST_4BB",
ip=192.168.10.111,
BSSID=d8:15:0d:4b:b7:a0}
可见手机流量走的是:ccmni0名称的ip
手机热点会产生一个ip: ap0名称的ip
都会有一个本地的ip地址:127.0.0.1
代码实现:这里用Properties盛放信息
判断网络类型需要的对象:
NetworkInfo
对象info
获取方法:通过Context获取系统服务
ConnectivityManager
再
getActiveNetworkInfo()
通过
info.getType()
:
移动网络2G/3G/4G:
ConnectivityManager.TYPE_MOBILE
WIFI:
ConnectivityManager.TYPE_WIFI
移动网络IP:获取
NetworkInterface
对象
获取NetworkInterface迭代枚举nis:
NetworkInterface.getNetworkInterfaces()
获取InetAddress迭代枚举ias:
ni.getInetAddresses
WIFI:获取
WifiInfo
对象
获取方法:通过Context获取系统服务
WifiManager
再
getConnectionInfo()
/**
* 获取IPv4
*
* @param context
* @return
*/
public static Properties getIPAddress(Context context) {
//将ip信息保存在Properties对象中
Properties prop = new Properties();
//获取网络信息
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
//网络信息非空,并且已连接
if (info != null && info.isConnected()) {
//当前使用2G/3G/4G网络
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
try {
//获取NetworkInterface的迭代枚举
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {//开始迭代
NetworkInterface ni = nis.nextElement();//获取每一个NetworkInterface
//获取InetAddress的迭代枚举
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {//开始迭代
InetAddress ia = ias.nextElement();//获取每一个InetAddress
//只取IPv4
if (ia instanceof Inet4Address) {
//将属性设置到集合
prop.setProperty(ni.getDisplayName(), ia.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
//通过WIFI管理者获取Wifi信息
WifiInfo wifiInfo = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE))
.getConnectionInfo();
//将属性设置到集合
prop.setProperty("ip", int2StrIP(wifiInfo.getIpAddress()));//得到IPV4地址
prop.setProperty("name", wifiInfo.getSSID());
prop.setProperty("BSSID", wifiInfo.getBSSID());
prop.setProperty("Mac", wifiInfo.getMacAddress());
}
} else {
//当前无网络连接
prop.setProperty("ERROR", "请打开网络");
}
return prop;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String int2StrIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
使用:
Properties prop = IpUtils.getIPAddress(IPActivity.this);
Enumeration<?> names = prop.propertyNames();
while (names.hasMoreElements()) {
String s = (String) names.nextElement();
log.e("TAG",(s + "=" + prop.getProperty(s)) + "\n");
}