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


本文摘自网络,作者,侵删。


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 中基于 ip 地址的 http 请求限流

手撸Golang Go与微服务 saga模式之9 小结/gitee源码

Go微服务框架Go-micro整体架构介绍

Golang怎么编写php扩展

为什么选择 Golang?彻底解决争论

解决Go升级到1.14后无法debug

Golang usr/local/Go/pkg/tool/linux_amd64/link: fingerprint mismatch 解决办法

近期面试回顾

Go-map

Goland解析json获取指定字段内容

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...