由于开发需要获取以太网的IP信息,设置静态IP等功能特此记录。
首先我们需要申请权限
tools:ignore="ProtectedPermissions" />
这个操作需要有自己编译的系统包,或者将对应 的SDK中的platforms\android-23\data\layoutlib.jar导入,同样上篇wifi中也可以这样,
private void setEthernetInfo(){
Boolean isethernetconnecyt = false;
String ethernetIp = getEthernetIpAddress();//IP
String ethernetMac = "";//MAC
String ethernetDNS = "";//DNS
String ethernetGateway = "";//网关
String ethernetMask = "";//子网掩码
Boolean isDHCP = true;//是否动态
if( ethernetIp != null && !ethernetIp.isEmpty()){//判断是否有网络连接
if (ethernetAdmin.getethernetstatic()){//判断是否是静态IP
StaticIpConfiguration staticIpConfiguration = ethernetAdmin.getConfiguration().staticIpConfiguration;
isDHCP = false;
//获取静态IP设置的网络信息
ethernetDNS = staticIpConfiguration.dnsServers.iterator().toString();
ethernetGateway = staticIpConfiguration.gateway.getHostAddress();
ethernetMask = utils.getMaskUtil(staticIpConfiguration.ipAddress.getNetworkPrefixLength());
Iterator dns = staticIpConfiguration.dnsServers.iterator();
if(dns.hasNext()){
ethernetDNS = dns.next().getHostAddress();
}
}else{
isDHCP = true;
//获取动态IP设置的网络信息
ethernetMask = SystemProperties.get("dhcp.eth0.mask");
ethernetGateway = SystemProperties.get("dhcp.eth0.gateway");
ethernetDNS = SystemProperties.get("dhcp.eth0.dns1");
}
}else{
//无网络连接
}
ethernetMac = getEthernetMAC();
}
//获取以太网的IP地址
public String getEthernetIpAddress() {
mConnectivityManager = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
LinkProperties linkProperties =
mConnectivityManager.getLinkProperties(ConnectivityManager.TYPE_ETHERNET);
for (LinkAddress linkAddress: linkProperties.getAllLinkAddresses()) {
InetAddress address = linkAddress.getAddress();
if (address instanceof Inet4Address) {
return address.getHostAddress();
}
}
// IPv6 address will not be shown like WifiInfo internally does.
return "";
}
//获取以太网的mac地址
public String getEthernetMAC(){
mEthernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
return mEthernetManager.getMacAddress();
}
//上图中子网掩码换算
public String getMaskUtil(int lenth){
lenth = (-1 >> (31-(lenth-1))) << (31-(lenth-1));
StringBuilder maskStr = new StringBuilder();
byte[] maskIp = new byte[4];
for (int i=0; i
maskIp[i] = (byte)(lenth>>(maskIp.length-1-i)*8);
maskStr.append((maskIp[i] & 0xff));
if (i < maskIp.length-1) {maskStr.append(".");}
}
return maskStr.toString();
}