一、題目
路由表最長匹配:將目標IP地址dstIP與路由為entryIP/掩碼長度m(比如10.166.50.0/23)進行匹配,找出匹配掩碼m最長值。
匹配規則:
如果dstIP和entryIP的二進制表示的前m個位相同,則說明是匹配的。
0.0.0.0是默認路由,與任何dstIP均匹配,m值為0。
所有匹配的路由中,m的最大值即為“最長匹配”。
二、樣例
第一行是dstIP
第二行是總entryIP數
第三行之后是具體的entryIP/m
192.168.0.3
6
10.166.50.0/23
192.0.0.0/0
10.255.255.255/32
192.168.0.1/24
127.0.0.0/0
192.168.0.0.0/24
輸出
192.168.0.1/24
三、代碼實現
// ipTable是個二維數組,每一個數組中第0列存IP,第1列存掩碼private static String routeSearch(String dstIp, String[][] ipTable) {String dstIpBinary = getRoute(dstIp);LinkedList<String> maxMatchList = new LinkedList<>();int maxMatch = -1;for (String[] strings : ipTable) {String tempRoute = strings[0];int maxNum = Integer.parseInt(strings[1]);if (tempRoute.equals("0.0.0.0") && maxNum == 0) {maxMatch = maxNum;maxMatchList.add(tempRoute + "/" + maxNum);continue;}if (isMatch(dstIpBinary, getRoute(tempRoute), maxNum) && maxNum > maxMatch) {maxMatchList.clear();maxMatch = maxNum;maxMatchList.add(tempRoute + "/" + maxNum);}}if (maxMatchList.isEmpty()) {return "empty";}return maxMatchList.getFirst();}// 判斷在給定matchNum長度下,是否匹配private static boolean isMatch(String src, String ds, int matchNum) {for (int i = 0; i < matchNum; i++) {if (src.charAt(i) != ds.charAt(i)) {return false;}}return true;}// 將IP地址轉換成二進制private static String getRoute(String s) {String[] ipSplit = s.split("\\.");StringBuilder stringBuilder = new StringBuilder();for (String ip : ipSplit) {// 轉換成二進制,不足8位,則補0String binaryString = Integer.toBinaryString(Integer.parseInt(ip));String formatBinaryStr = String.format("%8s", binaryString);formatBinaryStr = formatBinaryStr.replace(" ", "0");stringBuilder.append(formatBinaryStr);}return stringBuilder.toString();}