Golang Ip地址字符串整数string Int相互转换

大地缸 · · 1955 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。


title: "Golang Ip地址字符串整数string Int相互转换"
date: 2021-01-29T21:06:57+08:00
draft: true
tags: ['go']
author: "dadigang"
author_cn: "大地缸"
personal: "http://www.real007.cn"


关于作者

http://www.real007.cn/about

Go IP 地址字符串整数/string int 相互转换

Go 中没有 C 语言 inet_aton 和 inet_ntoa 类似的转换 IP 函数,

所以需要手动封装两个函数

(转换的方法有多种,我选择了简洁的)

实现如下:

package main

import (
    "fmt"
    "math/big"
    "net"
)

func InetNtoA(ip int64) string {
    return fmt.Sprintf("%d.%d.%d.%d",
        byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

func InetAtoN(ip string) int64 {
    ret := big.NewInt(0)
    ret.SetBytes(net.ParseIP(ip).To4())
    return ret.Int64()
}

func main() {
    ip := "192.168.78.123"
    ipInt := InetAtoN(ip)

    fmt.Printf("convert string ip [%s] to int: %d\n", ip, ipInt)
    fmt.Printf("convert int ip [%d] to string: %s\n", ipInt, InetNtoA(ipInt))
}

**注:**InetAtoN 最好加安全验证,检查 IP 字符串的有效性, 可以判断 net.ParseIP(ip).To4() 是否为 nil


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:大地缸

查看原文:Golang Ip地址字符串整数string Int相互转换

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1955 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传