Skip to content

Instantly share code, notes, and snippets.

@mapix
Created February 4, 2015 09:48
Show Gist options
  • Select an option

  • Save mapix/a7105437c34bf229c0e0 to your computer and use it in GitHub Desktop.

Select an option

Save mapix/a7105437c34bf229c0e0 to your computer and use it in GitHub Desktop.
package main
import "net"
import "fmt"
import "strconv"
import "strings"
func main() {
b, _ := IPToUint("111.11.191.17")
fmt.Println("111.11.191.17")
fmt.Println(b)
fmt.Println(UintToIP(b))
}
func IPToUint(ipstr string) (uint64, error) {
ip := net.ParseIP(ipstr)
ip4 := ip.To4()
if ip4 == nil {
return 0, fmt.Errorf("illegal: %v", ip)
}
bin := make([]string, len(ip4))
for i, v := range ip4 {
bin[i] = fmt.Sprintf("%08b", v)
}
return strconv.ParseUint(strings.Join(bin, ""), 2, 64)
}
func UintToIP(ip_uint uint64) (string, error) {
result := make(net.IP, 4)
for i := 0; i < 4; i++ {
result[3-i] = byte((ip_uint >> uint(8*i)) & 0xff)
}
return result.String(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment