Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

manet: add function to test if address is NAT64 IPv4 converted IPv6 address #202

Merged
merged 1 commit into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions net/ip.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package manet

import (
"bytes"
"net"

ma "github.com/multiformats/go-multiaddr"
Expand Down Expand Up @@ -116,3 +117,14 @@ func zoneless(m ma.Multiaddr) ma.Multiaddr {
return m
}
}

var NAT64WellKnownPrefix = [4]byte{0x0, 0x64, 0xff, 0x9b}

// IsNAT64IPv4ConvertedIPv6Addr returns whether addr is an IPv6 address that begins with
// the well-known prefix "64:ff9b" used for NAT64 Translation
// see RFC 6052
func IsNAT64IPv4ConvertedIPv6Addr(addr ma.Multiaddr) bool {
c, _ := ma.SplitFirst(addr)
return c != nil && c.Protocol().Code == ma.P_IP6 &&
bytes.HasPrefix(c.RawValue(), NAT64WellKnownPrefix[:])
}
44 changes: 44 additions & 0 deletions net/ip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package manet

import (
"fmt"
"testing"

ma "github.com/multiformats/go-multiaddr"
)

func TestIsWellKnownPrefixIPv4ConvertedIPv6Address(t *testing.T) {
cases := []struct {
addr ma.Multiaddr
want bool
failureReason string
}{
{
addr: ma.StringCast("/ip4/1.2.3.4/tcp/1234"),
want: false,
failureReason: "ip4 addresses should return false",
},
{
addr: ma.StringCast("/ip6/1::4/tcp/1234"),
want: false,
failureReason: "ip6 addresses doesn't have well-known prefix",
},
{
addr: ma.StringCast("/ip6/::1/tcp/1234"),
want: false,
failureReason: "localhost addresses should return false",
},
{
addr: ma.StringCast("/ip6/64:ff9b::192.0.1.2/tcp/1234"),
want: true,
failureReason: "ip6 address begins with well-known prefix",
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
if IsNAT64IPv4ConvertedIPv6Addr(tc.addr) != tc.want {
t.Fatalf("%s %s", tc.addr, tc.failureReason)
}
})
}
}