IPv4Tools { public static String patternMatchHost(TrieParserReader reader, int token, List<InetAddress> addrList) { String bindHost; if (addrList.isEmpty()) { bindHost = "127.0.0.1"; } else { InetAddress selected = null; if (token>=0) { for(int i=0; i<addrList.size(); i++) { InetAddress item = addrList.get(i); byte[] addr = item.getAddress(); boolean matches = true; for(int j=0; j<token; j++) { matches &= (((byte)reader.capturedLongField(reader, j)) == addr[0]); } if (matches) { selected = item; break; } } if (null==selected) { selected = IPv4Tools.selectExternalAddress(addrList); } } else { selected = IPv4Tools.selectExternalAddress(addrList); } bindHost = selected.toString().replace("/", ""); } return bindHost; }  static TrieParser buildAddressParser(); static String patternMatchHost(TrieParserReader reader, int token, List<InetAddress> addrList); static InetAddress selectExternalAddress(List<InetAddress> addrList); static TrieParser addressParser; }
@Test public void matchTest() { TrieParserReader reader = new TrieParserReader(true); assertEquals(4, reader.query(IPv4Tools.addressParser, "1.2.3.4")); assertEquals(3, reader.query(IPv4Tools.addressParser, "5.6.7.*")); assertEquals(2, reader.query(IPv4Tools.addressParser, "8.9.*.*")); assertEquals(1, reader.query(IPv4Tools.addressParser, "10.*.*.*")); assertEquals(0, reader.query(IPv4Tools.addressParser, "*.*.*.*")); int token = (int)reader.query(IPv4Tools.addressParser, "8.9.*.*"); List<InetAddress> addrList = new ArrayList<InetAddress>(); try { addrList.add(InetAddress.getByAddress("aaa",new byte[]{(byte)1,(byte)2,(byte)3,(byte)4})); addrList.add(InetAddress.getByAddress("bbb",new byte[]{(byte)8,(byte)9,(byte)3,(byte)4})); addrList.add(InetAddress.getByAddress("ccc",new byte[]{(byte)10,(byte)2,(byte)3,(byte)4})); } catch (UnknownHostException e) { e.printStackTrace(); } String host = IPv4Tools.patternMatchHost(reader, token, addrList); assertEquals("bbb8.9.3.4",host); }