Created
October 21, 2019 20:55
-
-
Save saffetblt/5fa80b18b292b79044ff0839fec6f5de to your computer and use it in GitHub Desktop.
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 ( | |
"errors" | |
"fmt" | |
"net" | |
"regexp" | |
"strings" | |
) | |
func main() { | |
isPrivate, _ := PrivateIP("192.168.1.6") | |
isIPv4 := ValidIP4("185.123.045.223") | |
fmt.Println(isPrivate) | |
fmt.Println(isIPv4) | |
} | |
func PrivateIP(ip string) (bool, error) { | |
var err error | |
private := false | |
IP := net.ParseIP(ip) | |
if IP == nil { | |
err = errors.New("Invalid IP") | |
} else { | |
_, private24BitBlock, _ := net.ParseCIDR("10.0.0.0/8") | |
_, private20BitBlock, _ := net.ParseCIDR("172.16.0.0/12") | |
_, private16BitBlock, _ := net.ParseCIDR("192.168.0.0/16") | |
private = private24BitBlock.Contains(IP) || private20BitBlock.Contains(IP) || private16BitBlock.Contains(IP) | |
} | |
return private, err | |
} | |
func ValidIP4(ipAddress string) bool { | |
ipAddress = strings.Trim(ipAddress, " ") | |
re, _ := regexp.Compile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`) | |
if re.MatchString(ipAddress) { | |
return true | |
} | |
return false | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment