android 静态消息 动态消息?,android 以太网(ethernet)获取静态信息和动态信息.IP.子网掩码.getaway(以太网 一)...

由于开发需要获取以太网的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();

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值