Created
February 4, 2015 09:48
-
-
Save mapix/a7105437c34bf229c0e0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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