Created
May 8, 2019 07:42
-
-
Save iraniamir/d9218f0574293b9bc7564c532c24b459 to your computer and use it in GitHub Desktop.
IPv4 to Mongo ObjectID
This file contains 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 ( | |
"encoding/hex" | |
"fmt" | |
"strings" | |
"gopkg.in/mgo.v2/bson" | |
) | |
func main() { | |
fmt.Print(IPv4ToObjectID("127.0.0.1")) | |
fmt.Print(IPv4ToObjectID("255.255.255.255")) | |
} | |
func IPv4ToObjectID(IP string) bson.ObjectId { | |
ip := strings.Replace(IP, ".", "", -1) | |
ipLen := len(ip) | |
if ipLen < 12 { | |
ip = ip + strings.Repeat("0", 12-ipLen) | |
} else if len(ip) > 12 { | |
ip = ip[:12] | |
} | |
encodedIP := hex.EncodeToString([]byte(ip)) | |
return bson.ObjectIdHex(encodedIP) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment