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

Ensure that the local IP address is global unicast #861

Merged
merged 2 commits into from
Sep 3, 2014
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
25 changes: 18 additions & 7 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 it is IPv4
// and assert that it is IPv4 and global unicast
ip, _, err := net.ParseCIDR(addr.String())
if err == nil && ip.To4() != nil {
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
37 changes: 37 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,39 @@ 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},

// loopback IPv4/6 unusable
{net.ParseIP("127.0.0.12"), false},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a loopback. The link-local IPv4 have the 169.254 prefix.

{net.ParseIP("::1"), false},

// link-local IPv4/6 unusable
{net.ParseIP("169.254.4.87"), false},
{net.ParseIP("fe80::12"), 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)
}
}
}