android 以太网(ethernet)设置静态信息和动态信息.IP.子网掩码.getaway(以太网 二)

上篇介绍了以太网信息获取,这篇介绍以太网信息获取,这篇直接贴设置代码

上篇地址:https://blog.csdn.net/qq_35345103/article/details/84573021

//设置静态IP信息 
public void processIpSettings(String etherentip,String etherentmasks,
                                  String etherentgeteway,String etherentdns) {

        IpConfiguration ipConfiguration = getConfiguration();

        ipConfiguration.setIpAssignment(IpConfiguration.IpAssignment.STATIC);
        ipConfiguration.setProxySettings(ipConfiguration.getProxySettings());

        StaticIpConfiguration staticConfig = new StaticIpConfiguration();
        Inet4Address inetAddr = null;
        try {
            inetAddr = (Inet4Address) NetworkUtils.numericToInetAddress(etherentip);
        } catch (IllegalArgumentException|ClassCastException e) {

        }

        int wasks = util.twoget(etherentmasks);
        try {
            staticConfig.ipAddress = new LinkAddress(inetAddr, wasks);
        } catch (NumberFormatException e) {

        }

        if (!TextUtils.isEmpty(etherentgeteway)) {
            try {
                staticConfig.gateway =(Inet4Address) NetworkUtils.numericToInetAddress(etherentgeteway);
            } catch (IllegalArgumentException|ClassCastException e) {
            }
        }

        if (!TextUtils.isEmpty(etherentdns)) {

            try {
                staticConfig.dnsServers.add(
                        (Inet4Address) NetworkUtils.numericToInetAddress(etherentdns));
            } catch (IllegalArgumentException|ClassCastException e) {

            }
        }
        ipConfiguration.setStaticIpConfiguration(staticConfig);
          getmEthernetManager().setConfiguration(ipConfiguration);
    }
//设置为动态IP
public void setEthernetDhcp(){
        IpConfiguration ipConfiguration = getConfiguration();
        if(getethernetstatic()) {
            ipConfiguration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
            mEthernetManager.setConfiguration(ipConfiguration);
        }
    }
   //获取以太网服务
 public EthernetManager  getmEthernetManager(){
      mEthernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
        return mEthernetManager;
    }

//解析子网掩码为数字

public  int twoget( String netwak){
        int wak = 0;

        if(netwak==null){
            return 24;
        }
        StringBuffer netmask = new StringBuffer();
        String[] ipArray = netwak.split("\\.");

        for (int j = 0; j < ipArray.length; j++) {
            String s = ipArray[j];
            String a=Integer.toBinaryString(Integer.valueOf(s));
            String aString2[]=a.split("");
            for (int i = 0; i < aString2.length; i++) {
                if ("1".equals(aString2[i])) {
                    wak++;
                }
            }
        }
        if(wak<=0 && wak>32){
            return 24;
        }

        return wak;


    }

 

你可能感兴趣的:(安卓)