Android以太网固定ip

索大镇楼

最近有个需求,固定以太网的ip。研究了,发现Android 把EthernetManager这个类给隐藏了,需要编译的源码(项目里面有)

代码如下
主界面:


import android.app.Activity;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.LinkAddress;
import android.net.StaticIpConfiguration;
import android.os.Bundle;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.Inet4Address;
import java.net.InetAddress;

import static com.ys.setstaticip.NetUtils.getIPv4Address;

public class MainActivity extends Activity {


    StaticIpConfiguration mStaticIpConfiguration;

    IpConfiguration mIpConfiguration;
    EthernetManager mEthManager;

    private  static String mEthIpAddress = "192.168.88.154";  //IP
    private  static String mEthNetmask = "255.255.255.0";  //  子网掩码
    private  static String mEthGateway = "192.168.88.1";   //网关
    private  static String mEthdns1 = "8.8.8.8";   // DNS1
    private  static String mEthdns2 = "8.8.4.4";   // DNS2

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStaticIP();
    }

    private void setStaticIP() {
        mEthManager = (EthernetManager) getSystemService("ethernet");
        mStaticIpConfiguration = new StaticIpConfiguration();
        /*
          * get ip address, netmask,dns ,gw etc.
          */
        Inet4Address inetAddr = getIPv4Address(mEthIpAddress);
        int prefixLength = NetUtils.maskStr2InetMask(mEthNetmask);
        InetAddress gatewayAddr = getIPv4Address(mEthGateway);
        InetAddress dnsAddr = getIPv4Address(mEthdns1);

        if (inetAddr.getAddress().toString().isEmpty() || prefixLength ==0 || gatewayAddr.toString().isEmpty()
                || dnsAddr.toString().isEmpty()) {
           return;
        }

        Class<?> clazz = null;
        try {
            clazz = Class.forName("android.net.LinkAddress");
        } catch (Exception e) {
            // TODO: handle exception
        }

        Class[] cl = new Class[]{InetAddress.class, int.class};
        Constructor cons = null;

        //取得所有构造函数
        try {
             cons = clazz.getConstructor(cl);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //给传入参数赋初值
        Object[] x = {inetAddr, prefixLength};

        String dnsStr2 = mEthdns2;
        //mStaticIpConfiguration.ipAddress = new LinkAddress(inetAddr, prefixLength);
        try {
            mStaticIpConfiguration.ipAddress = (LinkAddress) cons.newInstance(x);
            Log.d("232323", "chanson 1111111");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        mStaticIpConfiguration.gateway=gatewayAddr;
        mStaticIpConfiguration.dnsServers.add(dnsAddr);

        if (!dnsStr2.isEmpty()) {
            mStaticIpConfiguration.dnsServers.add(getIPv4Address(dnsStr2));
        }

        Log.d("2312321", "chanson mStaticIpConfiguration  ====" + mStaticIpConfiguration);

        mIpConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.STATIC, IpConfiguration.ProxySettings.NONE, mStaticIpConfiguration, null);

        mEthManager.setConfiguration(mIpConfiguration);
    }

工具类:


public class NetUtils {
    /*
    * convert subMask string to prefix length
    */
    public static int maskStr2InetMask(String maskStr) {
        StringBuffer sb ;
        String str;
        int inetmask = 0;
        int count = 0;
        /*
         * check the subMask format
         */
        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("33333","subMask is error");
            return 0;
        }

        String[] ipSegment = maskStr.split("\\.");
        for(int n =0; n<ipSegment.length;n++) {
            sb = new StringBuffer(Integer.toBinaryString(Integer.parseInt(ipSegment[n])));
            str = sb.reverse().toString();
            count=0;
            for(int i=0; i<str.length();i++) {
                i=str.indexOf("1",i);
                if(i==-1)
                    break;
                count++;
            }
            inetmask+=count;
        }
        return inetmask;
    }


    public static Inet4Address getIPv4Address(String text) {
        try {
            return (Inet4Address) NetworkUtils.numericToInetAddress(text);
        } catch (IllegalArgumentException|ClassCastException e) {
            return null;
        }
    }

代码地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,005评论 25 709
  • 太长了,还是转载吧...今天在看博客的时候,无意中发现了@Trinea在GitHub上的一个项目Android开源...
    庞哈哈哈12138阅读 20,339评论 3 283
  • 微光晨起雾连霜,城河曲纵冰封藏。 倦意临心囊四海,途人惊扰一黄粱!
    寒易阅读 1,756评论 0 0
  • 如果你再高一点,你就能看到山下的屋子,灰色的瓦片,白色的墙面,你就能告诉我它们看起来像什么。 游饼是第一个靠在我...
    尕朶李阅读 3,177评论 6 8
  • 美不美? 其实是Photoshop使这个世界变得更美好。 明天我就要出发去世界上最美的温泉-棉花堡,开始一个人旅行...
    长腿菇凉阅读 4,057评论 1 5

友情链接更多精彩内容