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

 1//code from www.361way.com
 2package main
 3import (
 4    "bytes"
 5    "encoding/binary"
 6    "fmt"
 7    "net"
 8    "strconv"
 9)
10//ip到数字
11func ip2Long(ip string) uint32 {
12    var long uint32
13    binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
14    return long
15}
16//数字到IP
17func backtoIP4(ipInt int64) string {
18    // need to do two bit shifting and “0xff” masking
19    b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
20    b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
21    b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
22    b3 := strconv.FormatInt((ipInt & 0xff), 10)
23    return b0 + "." + b1 + "." + b2 + "." + b3
24}
25func main() {
26    result := ip2Long("98.138.253.109")
27    fmt.Println(result)
28    // or if you prefer the super fast way
29    faster := binary.BigEndian.Uint32(net.ParseIP("98.138.253.109")[12:16])
30    fmt.Println(faster)
31    faster64 := int64(faster)
32    fmt.Println(backtoIP4(faster64))
33    ip1 := ip2Long("221.177.0.0")
34    ip2 := ip2Long("221.177.7.255")
35    //ip1 := ip2Long("192.168.0.0")
36    //ip2 := ip2Long("192.168.0.255")
37    x := ip2 - ip1
38    fmt.Println(ip1, ip2, x)
39    for i := ip1; i <= ip2; i++ {
40        i := int64(i)
41        fmt.Println(backtoIP4(i))
42    }
43}