jmpep / IPsubnet

IP subnet calculator IPv4 IPv6 HTML5 css bootstrap
MIT License
14 stars 4 forks source link

Missing IPv4 inside an IPv6 bytes to IPv4 converted #4

Open elico opened 5 years ago

elico commented 5 years ago

It would be nice to have the next function below embedded into this project in some way. I am working with maxmind Country lite DB and they store IPv4 and IPv6 on the same DB. For the data structure too stay consistent the library or the DB file stores the IPv4 in a 16 Bytes array instead of a 4 Bytes array. The original IPv4 CIDR address is: 1.0.128.0/17 However when I represent it as an IPv6 I recieve the next string: ::100:8000/113 . The Bytes array of this address is : [0 0 0 0 0 0 0 0 0 0 0 0 1 0 128 0] Since I am working with GoLang the only way I found was to write my own functions to convert this value into a visible IPv4 CIDR.

The next is my functions sources:

var v4InV6Array = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

func hasEmptyLeadingBytes(ip net.IP) bool {
    return equal(v4InV6Array, ip[0:12])
}

func fakeIPv6ToIPv4(ip net.IP) net.IP {
    if hasEmptyLeadingBytes(ip.To16()) {
        return ip[12:16]
    }
    return nil
}

func convertFakeV6ToV4(ip *net.IPNet) *net.IPNet {
    if hasEmptyLeadingBytes(ip.IP.To16()) {
        return &net.IPNet{IP: ip.IP[12:16], Mask: ip.Mask}
    }
    return ip
}