github.com/prysmaticlabs/prysm@v1.4.4/shared/iputils/external_ip_test.go (about)

     1  package iputils_test
     2  
     3  import (
     4  	"net"
     5  	"regexp"
     6  	"testing"
     7  
     8  	"github.com/prysmaticlabs/prysm/shared/iputils"
     9  	"github.com/prysmaticlabs/prysm/shared/testutil/assert"
    10  	"github.com/prysmaticlabs/prysm/shared/testutil/require"
    11  )
    12  
    13  func TestExternalIPv4(t *testing.T) {
    14  	// Regular expression format for IPv4
    15  	IPv4Format := `\.\d{1,3}\.\d{1,3}\b`
    16  	test, err := iputils.ExternalIPv4()
    17  	require.NoError(t, err)
    18  
    19  	valid := regexp.MustCompile(IPv4Format)
    20  	assert.Equal(t, true, valid.MatchString(test))
    21  }
    22  
    23  func TestRetrieveIP(t *testing.T) {
    24  	ip, err := iputils.ExternalIP()
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  	retIP := net.ParseIP(ip)
    29  	if retIP.To4() == nil && retIP.To16() == nil {
    30  		t.Errorf("An invalid IP was retrieved: %s", ip)
    31  	}
    32  }
    33  
    34  func TestSortAddresses(t *testing.T) {
    35  	testAddresses := []net.IP{
    36  		{0xff, 0x02, 0xAA, 0, 0x1F, 0, 0, 0, 0, 0, 0x02, 0x2E, 0, 0, 0x36, 0x45},
    37  		{0xff, 0x02, 0xAA, 0, 0x1F, 0, 0x2E, 0, 0, 0x36, 0x45, 0, 0, 0, 0, 0x02},
    38  		{0xAA, 0x11, 0x33, 0x19},
    39  		{0x01, 0xBF, 0x33, 0x10},
    40  		{0x03, 0x89, 0x33, 0x13},
    41  	}
    42  
    43  	sortedAddrs := iputils.SortAddresses(testAddresses)
    44  	assert.Equal(t, true, sortedAddrs[0].To4() != nil, "expected ipv4 address")
    45  	assert.Equal(t, true, sortedAddrs[1].To4() != nil, "expected ipv4 address")
    46  	assert.Equal(t, true, sortedAddrs[2].To4() != nil, "expected ipv4 address")
    47  	assert.Equal(t, true, sortedAddrs[3].To16() != nil && sortedAddrs[3].To4() == nil, "expected ipv6 address")
    48  	assert.Equal(t, true, sortedAddrs[4].To16() != nil && sortedAddrs[4].To4() == nil, "expected ipv6 address")
    49  }