ipv6最长前缀匹配算法

为什么80%的码农都做不了架构师?>>>   hot3.png

import java.net.Inet6Address;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;

public final class IPv6Base {

    private final class Node {
    
        private String info = null;
        private Node[] nodes = null;
        
        public Node() {}
        
        public void add(byte[] addr, int prefix, String info) {
            _add(0, addr, prefix, info);
        }
        
        public String get(byte[] addr) {
            Node ret = _get(0, addr);
            return null == ret ? null : ret.info;
        }
        
        private void _add(int index, byte[] addr, int prefix, String info) {
            if (null == nodes)
                nodes = new Node[512];
            int n = (addr[index] & 0x000000ff) | 0x00000100;
            if (prefix <= 8)
                n = n >> (8 - prefix);
            if (null == nodes[n])
                nodes[n] = new Node();
            if (prefix <= 8)
                nodes[n].info = info;
            else
                nodes[n]._add(index + 1, addr, prefix - 8, info);
        }
        
        private Node _get(int index, byte[] addr) {
            if (index > 7)
                return null;
            if (null == nodes)
                return null;
            final int n = (addr[index] & 0x000000ff) | 0x00000100;
            if (null != nodes[n]) {
                Node node = nodes[n]._get(index + 1, addr);
                if (null != node)
                    return node;
            }
            for (int i = 0; i < 8; i++) {
                int max = n >> i;
                if (null != nodes[max] && null != nodes[max].info)
                    return nodes[max];
            }
            return null;
        }
    }

    private Node entry = new Node();

    public void load(String dat) throws Exception {
        // load ipv6 info record from txt file `dat', like:
        // 2402:4E00:9000::/36\tChina,Guangdong,Shenzhen,telecom
        entry.add(Inet6Address.getByName("2402:4E00:9000::0").getAddress(), 36, "China,Guangdong,Shenzhen,telecom")
    }

    public String get(byte[] addr) throws Exception {
        return entry.get(addr);
    }
}

 

转载于:https://my.oschina.net/guzhou/blog/2988391

你可能感兴趣的:(ipv6最长前缀匹配算法)