Skip to content
This repository has been archived by the owner on Jan 30, 2020. It is now read-only.

Commit

Permalink
machine: testing of getLocalIP
Browse files Browse the repository at this point in the history
  • Loading branch information
bcwaldon committed Sep 3, 2014
1 parent e7fcbf8 commit 4a5ff21
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
23 changes: 17 additions & 6 deletions machine/coreos.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,27 +119,38 @@ func readLocalMachineID(root string) (string, error) {
return mID, nil
}

func getLocalIP() string {
func getLocalIP() (got string) {
iface := getDefaultGatewayIface()
if iface == nil {
return ""
return
}

addrs, err := iface.Addrs()
if err != nil || len(addrs) == 0 {
return ""
return
}

for _, addr := range addrs {
// Attempt to parse the address in CIDR notation
// and assert that it is IPv4 and global unicast
ip, _, err := net.ParseCIDR(addr.String())
if err == nil && ip.To4() != nil && ip.IsGlobalUnicast() {
return ip.String()
if err != nil {
continue
}

if !usableAddress(ip) {
continue
}

got = ip.String()
break
}

return ""
return
}

func usableAddress(ip net.IP) bool {
return ip.To4() != nil && ip.IsGlobalUnicast()
}

func getDefaultGatewayIface() *net.Interface {
Expand Down
33 changes: 33 additions & 0 deletions machine/coreos_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package machine

import (
"io/ioutil"
"net"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -49,3 +50,35 @@ func TestReadLocalMachineIDFound(t *testing.T) {
t.Fatalf("Received incorrect machID %q, expected 'pingpong'", machID)
}
}

func TestUsableAddress(t *testing.T) {
tests := []struct {
ip net.IP
ok bool
}{
// unicast IPv4 usable
{net.ParseIP("192.168.1.12"), true},

// unicast IPv6 unusable
{net.ParseIP("2001:DB8::3"), false},

// link-local IPv4/6 unusable
{net.ParseIP("127.0.0.12"), false},
{net.ParseIP("::1"), false},

// unspecified (all zeros) IPv4/6 unusable
{net.ParseIP("0.0.0.0"), false},
{net.ParseIP("::"), false},

// multicast IPv4/6 unusable
{net.ParseIP("239.255.255.250"), false},
{net.ParseIP("ffx2::4"), false},
}

for i, tt := range tests {
ok := usableAddress(tt.ip)
if tt.ok != ok {
t.Errorf("case %d: expected %v usable %t, got %t", i, tt.ip, tt.ok, ok)
}
}
}

0 comments on commit 4a5ff21

Please sign in to comment.