duanhu7400
2014-04-25 15:24
浏览 194

Golang Net.IP到IPv6(来自MySQL)作为十进制(39,0)转换?

I have a database that stores IPv4 and IPv6 addresses as decimal(39,0). I need to convert a Golang Net.IP to this format. I have done it for IPv4 as follows:

func ipv4ToInt(IPv4Addr net.IP) int64 {
    bits := strings.Split(IPv4Addr.String(), ".")

    b0, _ := strconv.Atoi(bits[0])
    b1, _ := strconv.Atoi(bits[1])
    b2, _ := strconv.Atoi(bits[2])
    b3, _ := strconv.Atoi(bits[3])

    var sum int64

    sum += int64(b0) << 24
    sum += int64(b1) << 16
    sum += int64(b2) << 8
    sum += int64(b3)

return sum
}

I am trying the same with IPv6:

func ipv6ToInt(IPv6Addr net.IP) Int128 {
    bits := strings.Split(IPv6Addr.String(), ":")
    var arr [4]int64
    var arr1 [4]uint64

    for i := 0; i < 4; i++ {
        arr[i], _ = strconv.ParseInt(bits[i], 16, 64)

    }

    for i := 0; i < 4; i++ {
    arr1[i], _ = strconv.ParseUint(bits[i], 16, 64)
    }

    int1 := arr[0]

    for i := 0; i < 4; i++ {
        int1 = (int1 << 16) + arr[i]
    }

    int2 := arr1[0]
    for i := 0; i < 4; i++ {
        int2 = (int2 << 16) + arr1[i]
    }

    var IPv6Int Int128
    IPv6Int.H = int1
    IPv6Int.L = int2
    return IPv6Int
}

Where int128 is

type Int128 struct {
    H int64
    L uint64
}

The result should look like:

42540578165168461141553663388954918914

from the IPv6 addr:

2001:470:0:76::2

Thanks!

EDIT, ANSWER: Thanks to the people in #go-nuts, the answer is as follows:

func ipv6ToInt(IPv6Addr net.IP) *big.Int {
    IPv6Int := big.NewInt(0)
    IPv6Int.SetBytes(IPv6Addr)
    return IPv6Int
} 

The same works for IPv6, just do IP.To4() first.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doucong3048 2014-05-02 17:50
    已采纳

    Thanks to the people in #go-nuts, the answer is as follows:

    func ipv6ToInt(IPv6Addr net.IP) *big.Int {
        IPv6Int := big.NewInt(0)
        IPv6Int.SetBytes(IPv6Addr)
        return IPv6Int
    } 
    

    The same works for IPv4, just do IP.To4() first.

    点赞 打赏 评论

相关推荐 更多相似问题