Skip to content

Commit

Permalink
Protect IPv6 last two octet
Browse files Browse the repository at this point in the history
  • Loading branch information
tsknadaj committed Oct 10, 2024
1 parent 81b86d6 commit 75aa499
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
14 changes: 13 additions & 1 deletion gdpr/protect_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gdpr
import (
"encoding/binary"
"net"
"net/netip"

"github.com/msales/gox/netx"
)
Expand All @@ -19,7 +20,18 @@ func ProtectIP[T IP](ip T) string {
case net.IP:
// if IP is v6, we don't do anything with it.
if cIP.To4() == nil {
return ""
cIP[12] = 0
cIP[13] = 0
cIP[14] = 0
cIP[15] = 0

addr, err := netip.ParseAddr(cIP.String())
// if there is an error, we don't do anything, we return empty value because something is wrong with passed ip
if err != nil {
return ""
}

return addr.StringExpanded()
}

// if ip is somehow empty, return empty string
Expand Down
2 changes: 1 addition & 1 deletion gdpr/protect_ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func Test_ProtectIP_String(t *testing.T) {
{
name: "raw ip v6",
ip: "2001:0000:130F:0000:0000:09C0:876A:130B",
want: "2001:0000:130F:0000:0000:09C0:0000:0000",
want: "2001:0000:130f:0000:0000:09c0:0000:0000",
},
}
for _, tt := range tests {
Expand Down

0 comments on commit 75aa499

Please sign in to comment.