Skip to content

Instantly share code, notes, and snippets.

@flydo
Created August 5, 2019 02:13
Show Gist options
  • Save flydo/26bcba7f7f962087255bb9eb25074ded to your computer and use it in GitHub Desktop.
Save flydo/26bcba7f7f962087255bb9eb25074ded to your computer and use it in GitHub Desktop.
IP2Long And Long2IP
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
)
func main() {
ipList := []string{
"255.255.255.255",
"localhost",
"127.0.0.1",
}
for _, v := range ipList {
long1 := IP2Long(v)
long2 := IP2Long2(v)
ip1 := Long2IP(long1)
ip2 := Long2IP(long2)
fmt.Printf("origin ip: %s, long1: %d, ip1: %s\n", v, long1, ip1)
fmt.Printf("origin ip: %s, long2: %d, ip2: %s\n\n", v, long2, ip2)
}
}
// IP2Long IP To Long
func IP2Long(ipstr string) uint32 {
ip := net.ParseIP(ipstr)
if ip == nil {
return 0
}
ip = ip.To4()
return binary.BigEndian.Uint32(ip)
}
// IP2Long2 IP To Long
func IP2Long2(ip string) uint32 {
var long uint32
binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
return long
}
// Long2IP Long To IP
func Long2IP(ipLong uint32) string {
ipByte := make([]byte, 4)
binary.BigEndian.PutUint32(ipByte, ipLong)
ip := net.IP(ipByte)
return ip.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment