前言:在Android 通过UDP广播建立Socket中介绍了通过在局域网内发UDP广播,返回同一局域网下,Wifi模块当前IP的方法。但是接下来又有新的问题,局域网内有多个这样的Wifi模块,还需要在一众IP+MAC的回复中过滤出指定MAC的IP。截取每条回复并用String.equal()查找虽然可行但是有点Low,还是用正则表达式匹配专业一些,逻辑更高、代码更简化、理解更容易。
一、 使用正则表达式匹配IP
- 将所有返回的IP+MAC存储到动态数组列表
byte[] receiveBuf = new byte[64];
int i = 0;
ArrayList arrayList=new ArrayList();
while(i<30) {
i++;
DatagramPacket receivePacket = new DatagramPacket(receiveBuf, receiveBuf.length);
try {
sendSocket.setSoTimeout(10);
sendSocket.receive(receivePacket);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String str=new String(receivePacket.getData(),"ASCII");
arrayList.add(str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Arrays.fill(receiveBuf, (byte)0);
}
- 遍历数组,正则匹配
int ii=0;
String[] addressTest = null;
String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}+[,]"+Launcher.Laucher_clicked_mac;
Pattern p = Pattern.compile(regex); //要匹配的正则表达式p
//遍历数组,查找匹配MAC
long sysData0 = System.currentTimeMillis();
for(ii=0; ii<arrayList.size();ii++) {
String arrayBuf = (String) arrayList.get(ii);
Matcher m = p.matcher(arrayBuf); // 等待匹配的文本m
boolean result = m.find();
while(result) {
addressTest = arrayList.get(ii).toString().split(",");
result = m.find();
break;
}
}
long sysData1 = System.currentTimeMillis();
System.out.print("搜索MAC耗时:"+(sysData1-sysData0)+"毫秒"+"\n");
- 找到IP
if(addressTest!=null){
System.out.print("已经找到了对应的MAC和IP");
address = addressTest[0].toString();
ipx = address;
System.out.print("返回IP:"+addressTest[0].toString());
}else{
System.out.print("搜索结果为空"+"\n");
}
二、参考资料
[1] http://www.ibm.com/developerworks/cn/java/l-regp/part1/
IBM developerWorks 深度好文,舔屏力荐
[2] http://blog.csdn.net/sq_zhuyi/article/details/12848509
正则入门
[3] http://blog.youxu.info/2009/03/05/ree1/
编程猪鸡番外篇——正则表达式入门