|
private ArrayList<String> getDeviceIPList() {
String localIp = Utils.getHostIP();
if (localIp != null) {
String s = "null";
DatagramPacket dp = new DatagramPacket(s.getBytes(), 0, s.length());
DatagramSocket socket = null;
String[] sp = localIp.split("\\.");
try {
socket = new DatagramSocket();
int position = 2;
while (position < 255) {
dp.setAddress(InetAddress.getByName(sp[0] + "." + sp[1] + "." + sp[2] + "." + String.valueOf(position)));
socket.send(dp);
position++;
if (position == 125) {//分两段掉包,一次性发的话,达到236左右,会耗时3秒左右再往下发
socket.close();
socket = new DatagramSocket();
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
BufferedReader br = null;
ArrayList<String> result = null;
try {
result = new ArrayList<>();
br = new BufferedReader(new FileReader("/proc/net/arp"));//读取这个文件
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");//将文件里面的字段分割开来
if (splitted.length >= 4 && splitted[3] != null && !splitted[3].equals("00:00:00:00:00:00")) {
// Basic sanity check
String mac = splitted[3];// 文件中分别是IP address HW type Flags HW address mask Device
//然后我们拿取HW address 也就是手机的mac地址进行匹配 如果有 就证明是手机
if (mac.matches("..:..:..:..:..:..")) {
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(1000);
if (!isReachable) {// 若isReachable不成立
Socket socket = null;
try {
socket = new Socket();
SocketAddress socAddress = new InetSocketAddress(InetAddress.getByName(splitted[0]), 554);
socket.connect(socAddress, 1500);
Log.i(TAG, "socket.isConnected():" + socket.isConnected() + "---ip--->" + splitted[0]);
if (socket.isConnected()) {
isReachable = true;
}
} catch (Exception e) {
Log.e(TAG, "" + e.toString());
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.i(TAG, "isReachable:" + isReachable + "--ip:" + splitted[0]);
if (isReachable) {
result.add(splitted[0]);//最后如果能匹配 那就证明是连接了热点的手机 加到这个集合里 里面有所有需要的信息
}
}
}
}
} catch (Exception e) {
Log.e(TAG, "ApTask.doInBackground.error " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
Log.e(TAG, "ApTask.doInBackground.error " + e.getMessage());
e.printStackTrace();
}
}
return result;
} |
|