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;
        }
    }

代碼地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,422評論 25 708
  • 太長了,還是轉載吧...今天在看博客的時候,無意中發現了@Trinea在GitHub上的一個項目Android開源...
    龐哈哈哈12138閱讀 20,274評論 3 283
  • 微光晨起霧連霜,城河曲縱冰封藏。 倦意臨心囊四海,途人驚擾一黃粱!
    寒易閱讀 257評論 0 0
  • 如果你再高一點,你就能看到山下的屋子,灰色的瓦片,白色的墻面,你就能告訴我它們看起來像什么。 游餅是第一個靠在我...
    尕朶李閱讀 448評論 6 8
  • 美不美? 其實是Photoshop使這個世界變得更美好。 明天我就要出發去世界上最美的溫泉-棉花堡,開始一個人旅行...
    長腿菇涼閱讀 752評論 1 5