From 12f28a662354337a9c655244821c95e5b72681f0 Mon Sep 17 00:00:00 2001 From: marko Date: Thu, 3 Oct 2024 17:46:43 +0200 Subject: [PATCH] added ipv4 validation --- chatbot/chatbot.go | 6 +++--- ping/ping.go | 10 ++++++++++ ping/ping_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 ping/ping_test.go diff --git a/chatbot/chatbot.go b/chatbot/chatbot.go index eba90ad..7227c36 100644 --- a/chatbot/chatbot.go +++ b/chatbot/chatbot.go @@ -86,13 +86,13 @@ func (nkbot *NekoUKrovuBot) handleChat(ch *xmpp.Chat) { func (nkbot *NekoUKrovuBot) sanitizeInput(input string) bool { if len(input) > 50 { - return false + return true } if !utf8.ValidString(input) { - return false + return true } - + return true } diff --git a/ping/ping.go b/ping/ping.go index fdd5d91..e460ba4 100644 --- a/ping/ping.go +++ b/ping/ping.go @@ -4,6 +4,7 @@ import ( "fmt" "net" "os/exec" + "regexp" "sync" ) @@ -56,7 +57,16 @@ func getNetworkPrefix(ip net.IP) string { return fmt.Sprintf("%d.%d.%d.0", ip[0], ip[1], ip[2]) } +func isValidIPv4(ip string) bool { + ipv4Regex := `^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$` + re := regexp.MustCompile(ipv4Regex) + return re.MatchString(ip) +} + func ping(ip string) bool { + if !isValidIPv4(ip) { + return false + } output, err := exec.Command("ping", "-c", "1", "-W", "1", ip).CombinedOutput() if err != nil { diff --git a/ping/ping_test.go b/ping/ping_test.go new file mode 100644 index 0000000..ca92442 --- /dev/null +++ b/ping/ping_test.go @@ -0,0 +1,25 @@ +package ping + +import "testing" + +func Test_isValidIPv4(t *testing.T) { + type args struct { + ip string + } + tests := []struct { + name string + args args + want bool + }{ + {name: "1", args: args{ip: "192.168.1.1"}, want: true}, + {name: "2", args: args{ip: "192.168.277.1"}, want: false}, + {name: "3", args: args{ip: "kurac palac"}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isValidIPv4(tt.args.ip); got != tt.want { + t.Errorf("isValidIPv4() = %v, want %v", got, tt.want) + } + }) + } +}