Android掃描局域網內全部的ip地址

代碼是直接複製過來的,沒保留源地址,對原做者表示歉意……java

代碼是直接能夠跑起來的,測試機是小米6,掃描一個局域網共255個ip地址,用時4.7秒左右!android

直接上代碼:windows

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.imxiaoyu.common.utils.ALog;

/**
 * Created by Admin on 2017/10/13.
 */

public class ScanDeviceUtile {

    private static final String TAG = ScanDeviceUtile.class.getSimpleName();

    /** 核心池大小 **/
    private static final int CORE_POOL_SIZE = 1;
    /** 線程池最大線程數 **/
    private static final int MAX_IMUM_POOL_SIZE = 255;

    private String mDevAddress;// 本機IP地址-完整
    private String mLocAddress;// 局域網IP地址頭,如:192.168.1.
    private Runtime mRun = Runtime.getRuntime();// 獲取當前運行環境,來執行ping,至關於windows的cmd
    private Process mProcess = null;// 進程
    private String mPing = "ping -c 1 -w 3 ";// 其中 -c 1爲發送的次數,-w 表示發送後等待響應的時間
    private List<String> mIpList = new ArrayList<String>();// ping成功的IP地址
    private ThreadPoolExecutor mExecutor;// 線程池對象

    /**
     * TODO<掃描局域網內ip,找到對應服務器>
     *
     * @return void
     */
    public List<String> scan() {
        mDevAddress = getHostIP();// 獲取本機IP地址
        mLocAddress = getLocAddrIndex(mDevAddress);// 獲取本地ip前綴
        ALog.e(TAG, "開始掃描設備,本機Ip爲:" + mDevAddress);

        if (TextUtils.isEmpty(mLocAddress)) {
            ALog.e(TAG, "掃描失敗,請檢查wifi網絡");
            return null;
        }

        /**
         * 1.核心池大小 2.線程池最大線程數 3.表示線程沒有任務執行時最多保持多久時間會終止
         * 4.參數keepAliveTime的時間單位,有7種取值,當前爲毫秒
         * 5.一個阻塞隊列,用來存儲等待執行的任務,這個參數的選擇也很重要,會對線程池的運行過程產生重大影響
         * ,通常來講,這裏的阻塞隊列有如下幾種選擇:
         */
        mExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_IMUM_POOL_SIZE,
                2000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(
                CORE_POOL_SIZE));

        // 新建線程池
        for (int i = 1; i < 255; i++) {// 建立256個線程分別去ping
            final int lastAddress = i;// 存放ip最後一位地址 1-255

            Runnable run = new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    String ping = ScanDeviceUtile.this.mPing + mLocAddress
                            + lastAddress;
                    String currnetIp = mLocAddress + lastAddress;
                    if (mDevAddress.equals(currnetIp)) // 若是與本機IP地址相同,跳過
                        return;

                    try {
                        mProcess = mRun.exec(ping);

                        int result = mProcess.waitFor();
//                        ALog.e(TAG, "正在掃描的IP地址爲:" + currnetIp + "返回值爲:" + result);
                        if (result == 0) {
//                            ALog.e(TAG, "掃描成功,Ip地址爲:" + currnetIp);
                            mIpList.add(currnetIp);
                        } else {
                            // 掃描失敗
//                            ALog.e(TAG, "掃描失敗");
                        }
                    } catch (Exception e) {
                        ALog.e(TAG, "掃描異常" + e.toString());
                    } finally {
                        if (mProcess != null)
                            mProcess.destroy();
                    }
                }
            };

            mExecutor.execute(run);
        }

        mExecutor.shutdown();

        while (true) {
            try {
                if (mExecutor.isTerminated()) {// 掃描結束,開始驗證
                    ALog.e(TAG, "掃描結束,總共成功掃描到" + mIpList.size() + "個設備.");
                    ALog.e("設備列表:"+new Gson().toJson(mIpList));
                    return mIpList;
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * TODO<銷燬正在執行的線程池>
     *
     * @return void
     */
    public void destory() {
        if (mExecutor != null) {
            mExecutor.shutdownNow();
        }
    }

    /**
     * TODO<獲取本地ip地址>
     *
     * @return String
     */
    private String getLocAddress() {
        String ipaddress = "";

        try {
            Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();
            // 遍歷所用的網絡接口
            while (en.hasMoreElements()) {
                NetworkInterface networks = en.nextElement();
                // 獲得每個網絡接口綁定的全部ip
                Enumeration<InetAddress> address = networks.getInetAddresses();
                // 遍歷每個接口綁定的全部ip
                while (address.hasMoreElements()) {
                    InetAddress ip = address.nextElement();
                    if (!ip.isLoopbackAddress()
                            && (ip instanceof Inet4Address)) {
                        ipaddress = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            ALog.e("", "獲取本地ip地址失敗");
            e.printStackTrace();
        }

        ALog.e(TAG, "本機IP:" + ipaddress);
        return ipaddress;
    }
    /**
     * 獲取ip地址
     * @return
     */
    public static String getHostIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            ALog.e("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;

    }
    /**
     * TODO<獲取本機IP前綴>
     *
     * @param devAddress
     *            // 本機IP地址
     * @return String
     */
    private String getLocAddrIndex(String devAddress) {
        if (!devAddress.equals("")) {
            return devAddress.substring(0, devAddress.lastIndexOf(".") + 1);
        }
        return null;
    }

}
相關文章
相關標籤/搜索