如何使用 golang 写 IP地址生成器

这个是同事提的一个需求,希望能给出一个开始地址和结束地址,能打印出两者之间的所有地址。这个本来可以简单的通过shell也可以完成(满255进1),不过刚好最近在学习golang,所以就想着用golang的位运算实现下ip地址的生成。原理也比较简单,先将IP地址数字化,通过循环遍历前后两个地址中间的数值,再将该数值转化为IP就OK了。代码如下:

//code from www.linuxprobe.com
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"strconv"
)
//ip到数字
func ip2Long(ip string) uint32 {
var long uint32
binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
return long
}
//数字到IP
func backtoIP4(ipInt int64) string {
// need to do two bit shifting and “0xff” masking
b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
b3 := strconv.FormatInt((ipInt & 0xff), 10)
return b0 + "." + b1 + "." + b2 + "." + b3
}
func main() {
result := ip2Long("98.138.253.109")
fmt.Println(result)
// or if you prefer the super fast way
faster := binary.BigEndian.Uint32(net.ParseIP("98.138.253.109")[12:16])
fmt.Println(faster)
faster64 := int64(faster)
fmt.Println(backtoIP4(faster64))
ip1 := ip2Long("221.177.0.0")
ip2 := ip2Long("221.177.7.255")
//ip1 := ip2Long("192.168.0.0")
//ip2 := ip2Long("192.168.0.255")
x := ip2 - ip1
fmt.Println(ip1, ip2, x)
for i := ip1; i < = ip2; i++ {
i := int64(i)
fmt.Println(backtoIP4(i))
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值