Skip to content

Commit

Permalink
Introduce IPValidation (#217)
Browse files Browse the repository at this point in the history
Co-authored-by: Robert Hoppe <[email protected]>
  • Loading branch information
roberth1988 and Robert Hoppe committed Jul 10, 2024
1 parent dd49f51 commit c0ad906
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package validate
import (
"fmt"
"io"
"net"
"net/http"
"reflect"
"regexp"
Expand Down Expand Up @@ -254,6 +255,18 @@ func Prefix(pr string) error {
return nil
}

// IsIP validates a given IP
func IsIP(pr string) error {
pr = strings.Trim(pr, "\"")

trial := net.ParseIP(pr)
if trial == nil {
return fmt.Errorf("given IP: %s. is not valid", pr)
}

return nil
}

// PublicIP validates a given ID address
func PublicIP(ip string) error {
exp := "((^\\s*((([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]))\\s*$)|(^\\s*((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$))"
Expand Down
22 changes: 22 additions & 0 deletions pkg/validate/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,28 @@ func TestPrefix(t *testing.T) {
}
}

func TestIP(t *testing.T) {
type args struct {
prefix string
}
tests := []struct {
name string
args args
wantErr bool
}{
{"not ok", args{"999.999.999.999"}, true},
{"ok [1]", args{"192.168.1.1"}, false},
{"ok [1]", args{"\"192.168.1.1\""}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validate.IsIP(tt.args.prefix); (err != nil) != tt.wantErr {
t.Errorf("IsIP() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

func TestPublicIP(t *testing.T) {
type args struct {
ip string
Expand Down

0 comments on commit c0ad906

Please sign in to comment.