duanhu7400 2014-04-25 15:24
浏览 226
已采纳

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题