栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 以太网Ethernet的静态ip和动态dhcp获取ip的相关接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 以太网Ethernet的静态ip和动态dhcp获取ip的相关接口

android系统中,针对以太网Ethernet的静态IP和动态Dhcp获取ip相关的接口:

package com.mili.systemutils.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.linkAddress;
import android.net.linkProperties;
import android.net.NetworkInfo;
import android.net.RouteInfo;
import android.net.StaticIpConfiguration;
import android.os.SystemProperties;
import android.os.Build;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import static android.content.Context.CONNECTIVITY_SERVICE;



public class EthernetUtils {

    private static final String TAG = "EthernetUtils";
    private final static String nullIpInfo = "0.0.0.0";

    
    public static final int NETWORK_TYPE_INVALID = 0;
    
    public static final int NETWORK_TYPE_ETHERNET = 1;
    
    public static final int NETWORK_TYPE_WIFI = 2;
    
    public static final int NETWORK_TYPE_2G = 3;
    
    public static final int NETWORK_TYPE_3G = 4;
    
    public static final int NETWORK_TYPE_WAP = 5;

    public class NetParam {
        private String ipAddr;
        private String gateway;
        private String netMask;
        private String dns1;
        private String dns2;

        public void setIpAddr(String ipAddrStr) {
            ipAddr = ipAddrStr;
        }

        public String getIpAddr() {
            return ipAddr;
        }

        public void setGateway(String gatewayStr) {
            gateway = gatewayStr;
        }

        public String getGateway() {
            return gateway;
        }

        public void setNetMask(String netMaskStr) {
            netMask = netMaskStr;
        }

        public String getNetMask() {
            return netMask;
        }

        public void setDns1(String dns1Str) {
            dns1 = dns1Str;
        }

        public String getDns1() {
            return dns1;
        }

        public void setDns2(String dns2Str) {
            dns2 = dns2Str;
        }

        public String getDns2() {
            return dns2;
        }
    }

    
    public String interMask2String(int prefixLength) {
        String netMask = null;
        int inetMask = prefixLength;

        int part = inetMask / 8;
        int remainder = inetMask % 8;
        int sum = 0;

        for (int i = 8; i > 8 - remainder; i--) {
            sum = sum + (int) Math.pow(2, i - 1);
        }

        if (part == 0) {
            netMask = sum + ".0.0.0";
        } else if (part == 1) {
            netMask = "255." + sum + ".0.0";
        } else if (part == 2) {
            netMask = "255.255." + sum + ".0";
        } else if (part == 3) {
            netMask = "255.255.255." + sum;
        } else if (part == 4) {
            netMask = "255.255.255.255";
        }

        return netMask;
    }

    
    public int maskStr2InetMask(String maskStr) {
        StringBuffer sb ;
        String str;
        int inetmask = 0;
        int count = 0;
    	
        Pattern pattern = Pattern.compile("(^((\d|[01]?\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[01]?\d\d|2[0-4]\d|25[0-5])$)|^(\d|[1-2]\d|3[0-2])$");
        if (pattern.matcher(maskStr).matches() == false) {
            Log.e(TAG,"subMask is error");
            return 0;
        }

        String[] ipSegment = maskStr.split("\.");
        for(int n =0; n 255) || (block < 0)) {
                    return false;
                }
            } catch (NumberFormatException e) {
                return false;
            }

            numBlocks++;

            start = end + 1;
            end = value.indexOf('.', start);
        }
        return numBlocks == 4;
    }

    
    public boolean setStaticIpConfiguration(Context context, NetParam netParam) {

        StaticIpConfiguration staticIpConfiguration = new StaticIpConfiguration();
        if (staticIpConfiguration == null) {
            return false;
        }

        if (context == null) {
            return false;
        }

        EthernetManager ethernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
        if (ethernetManager == null) {
            return false;
        }

        try {
            InetAddress inetAddr = InetAddress.getByName(netParam.getIpAddr());
            int prefixLength = maskStr2InetMask(netParam.getNetMask());
            InetAddress gatewayAddr = InetAddress.getByName(netParam.getGateway());
            InetAddress dnsAddr = InetAddress.getByName(netParam.getDns1());

            if (inetAddr.toString().isEmpty() || prefixLength == 0 || gatewayAddr.toString().isEmpty()
                    || dnsAddr.toString().isEmpty()) {
                Log.e(TAG, "ip,mask or dnsAddr is wrong");
                return false;
            }

            staticIpConfiguration.ipAddress = new linkAddress(inetAddr, prefixLength);
            staticIpConfiguration.gateway = gatewayAddr;
            staticIpConfiguration.domains = netParam.getNetMask();

            if (isIpAddress(netParam.getDns1())) {
                staticIpConfiguration.dnsServers.add(InetAddress.getByName(netParam.getDns1()));
            }
            if (isIpAddress(netParam.getDns2())) {
                staticIpConfiguration.dnsServers.add(InetAddress.getByName(netParam.getDns2()));
            }

            IpConfiguration ipConfiguration = new IpConfiguration();
            ipConfiguration.ipAssignment = IpConfiguration.IpAssignment.STATIC;
            ipConfiguration.proxySettings = IpConfiguration.ProxySettings.NONE;
            ipConfiguration.staticIpConfiguration = staticIpConfiguration;
            ipConfiguration.httpProxy = null;

//            ipConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.STATIC, IpConfiguration.ProxySettings.NONE, staticIpConfiguration, null);
            if (ipConfiguration == null) {
                return false;
            }
            ethernetManager.setConfiguration(ipConfiguration);
        } catch (UnknownHostException e) {
            return false;
        }
        return true;
    }

    
    public boolean setDhcpIpConfiguration(Context context) {
        if (context == null) {
            return false;
        }

        EthernetManager ethernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
        if (ethernetManager == null) {
            return false;
        }

        ethernetManager.setConfiguration(new IpConfiguration(IpConfiguration.IpAssignment.DHCP, IpConfiguration.ProxySettings.NONE, null, null));
        return true;
    }

    
    public NetParam getEthInfoFromDhcp(){
        NetParam netParam = new NetParam();
        String tempIpInfo;
        String iface = "eth0";

        tempIpInfo = SystemProperties.get("dhcp."+ iface +".ipaddress");
        Log.d("EthernetUtils", "tempIpInfo :" + tempIpInfo);
        if ((tempIpInfo != null) && (!tempIpInfo.equals("")) ){
            netParam.setIpAddr(tempIpInfo);
        } else {
            netParam.setIpAddr(nullIpInfo);
        }

        tempIpInfo = SystemProperties.get("dhcp."+ iface +".mask");
        if ((tempIpInfo != null) && (!tempIpInfo.equals("")) ){
            netParam.setNetMask(tempIpInfo);
        } else {
            netParam.setNetMask(nullIpInfo);
        }

        tempIpInfo = SystemProperties.get("dhcp."+ iface +".gateway");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))){
            netParam.setGateway(tempIpInfo);
        } else {
            netParam.setGateway(nullIpInfo);
        }

        tempIpInfo = SystemProperties.get("dhcp."+ iface +".dns1");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))){
            netParam.setDns1(tempIpInfo);
        } else {
            netParam.setDns1(nullIpInfo);
        }

        tempIpInfo = SystemProperties.get("dhcp."+ iface +".dns2");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))){
            netParam.setDns2(tempIpInfo);
        } else {
            netParam.setDns2(nullIpInfo);
        }

        return netParam;
    }

    
    public EthernetUtils.NetParam getEthInfoFromDhcp(Context context) {
        if (context == null) {
            return null;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            Log.d(TAG, "connectivityManager is null");
            return null;
        }
        linkProperties linkProperties = null;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            linkProperties = connectivityManager.getlinkProperties(connectivityManager.getActiveNetwork());
        }
        if (linkProperties == null) {
            Log.d(TAG, "linkProperties is null");
            return null;
        }
        Log.d(TAG, linkProperties.toString());

        EthernetUtils ethernetUtils = new EthernetUtils();
        EthernetUtils.NetParam netParam = ethernetUtils.new NetParam();

        List ipAddress = linkProperties.getlinkAddresses();
        if (ipAddress != null && ipAddress.size() > 0) {
            int size = ipAddress.size();
            netParam.setIpAddr(ipAddress.get(size-1).getAddress().getHostAddress());
            netParam.setNetMask(interMask2String(ipAddress.get(size-1).getPrefixLength()));
        }

        List routeInfos = linkProperties.getRoutes();
        if (routeInfos != null && routeInfos.size() > 1) {
            int size = routeInfos.size();
            netParam.setGateway(routeInfos.get(size-1).getGateway().getHostAddress());
        }

        List dnsServers = linkProperties.getDnsServers();
        if (dnsServers != null && dnsServers.size() > 0) {
            netParam.setDns1(dnsServers.get(0).getHostAddress());
            if (dnsServers.size() > 1) {
                netParam.setDns2(dnsServers.get(1).getHostAddress());
            }
        }

        Log.d(TAG, "Ipaddr:" + netParam.getIpAddr() + ", netmask:"
                + netParam.getNetMask() + ", gateway:" + netParam.getGateway() + ", dns1:"
                + netParam.getDns1() + ", dns2:" + netParam.getDns2());

        return netParam;
    }

    
    public NetParam getEthInfoFromStaticIp(Context context) {
        if (context == null) {
            return null;
        }

        EthernetManager ethernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
        if (ethernetManager == null) {
            return null;
        }

        StaticIpConfiguration staticIpConfiguration = ethernetManager.getConfiguration().getStaticIpConfiguration();
        if(staticIpConfiguration == null) {
            return null;
        }

        NetParam netParam = new NetParam();

        linkAddress ipAddress = staticIpConfiguration.ipAddress;
        InetAddress gateway   = staticIpConfiguration.gateway;
        ArrayList dnsServers = staticIpConfiguration.dnsServers;

        if( ipAddress != null) {
            netParam.setIpAddr(ipAddress.getAddress().getHostAddress());
            netParam.setNetMask(interMask2String(ipAddress.getPrefixLength()));
        }
        if(gateway != null) {
            netParam.setGateway(gateway.getHostAddress());
        }
        netParam.setDns1(dnsServers.get(0).getHostAddress());

        if(dnsServers.size() > 1) { 
            netParam.setDns2(dnsServers.get(1).getHostAddress());
        }

        return netParam;
    }

    
    public int getEthUseDhcpOrStaticIp(Context context) {
        if (context == null) {
            return 0;
        }

        EthernetManager ethernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
        if (ethernetManager == null) {
            return 0;
        }

        IpConfiguration.IpAssignment ipAssignment = ethernetManager.getConfiguration().ipAssignment;
        if (ipAssignment == IpConfiguration.IpAssignment.STATIC) {
            return 1;
        } else if (ipAssignment == IpConfiguration.IpAssignment.DHCP) {
            return 2;
        }
        return 0;
    }

    
    public String getMacAddress() {
        try {
            return loadFileAsString("/sys/class/net/eth0/address").toUpperCase(Locale.ENGLISH).substring(0, 17);
        } catch (IOException e) {
            return null;
        }
    }

    private String loadFileAsString(String filePath) throws IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024]; int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        String mac = fileData.toString();
//        ProviderUtil.setValue(mContext, ProviderUtil.Name.ETHERNET_MAC, mac);
        if (mac == null) {
            mac = "00:00:00:00:00:00";
        }
        return mac;
    }

    
    public int getNetWorkType(Context context) {
        int mNetWorkType = NETWORK_TYPE_INVALID;
        if (context == null) {
            return mNetWorkType;
        }
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()){
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("ETHERNET")) {
                mNetWorkType = NETWORK_TYPE_ETHERNET;
            } else if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = NETWORK_TYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
//                String proxyHost = android.net.Proxy.getDefaultHost();
//                mNetWorkType = TextUtils.isEmpty(proxyHost)
//                        ? (isFastMobileNetwork() ? NETWORK_TYPE_3G : NETWORK_TYPE_2G)
//                        : NETWORK_TYPE_WAP;
            }
        }
        return mNetWorkType;
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/445448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号