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

這個是同事提的一個需求,希望能給出一個開始地址和結束地址,能打印出兩者之間的所有地址。這個本來可以簡單的通過shell也可以完成(滿255進1),不過剛好最近在學習golang,所以就想着用golang的位運算實現下ip地址的生成。原理也比較簡單,先將IP地址數字化,通過循環遍歷前後兩個地址中間的數值,再將該數值轉化爲IP就OK了。代碼如下:

//code from www.[linux](https://www.linuxprobe.com/ "linux")probe.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))
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章