-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathmain.go
More file actions
93 lines (86 loc) · 2.13 KB
/
main.go
File metadata and controls
93 lines (86 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (c) 2014 Kelsey Hightower. All rights reserved.
// Use of this source code is governed by the Apache License, Version 2.0
// that can be found in the LICENSE file.
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"github.com/docker/libcontainer/netlink"
)
var (
defaultEnvironmentFilePath = "/etc/network-environment"
environmentFilePath string
)
func init() {
log.SetFlags(0)
flag.StringVar(&environmentFilePath, "o", defaultEnvironmentFilePath, "environment file")
}
func main() {
flag.Parse()
tempFilePath := environmentFilePath + ".tmp"
tempFile, err := os.Create(tempFilePath)
if err != nil {
log.Fatal(err)
}
defer tempFile.Close()
if err := writeEnvironment(tempFile); err != nil {
log.Fatal(err)
}
os.Rename(tempFilePath, environmentFilePath)
}
func writeEnvironment(w io.Writer) error {
var buffer bytes.Buffer
defaultIfaceName, err := getDefaultGatewayIfaceName()
if err != nil {
// A default route is not required; log it and keep going.
log.Println(err)
}
interfaces, err := net.Interfaces()
if err != nil {
return err
}
for _, iface := range interfaces {
addrs, err := iface.Addrs()
if err != nil {
return err
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
// Record IPv4 network settings. Stop at the first IPv4 address
// found for the interface.
if err == nil && ip.To4() != nil {
buffer.WriteString(fmt.Sprintf("%s_IPV4=%s\n", strings.Replace(strings.ToUpper(iface.Name), ".", "_", -1), ip.String()))
if defaultIfaceName == iface.Name {
buffer.WriteString(fmt.Sprintf("DEFAULT_IPV4=%s\n", ip.String()))
}
break
}
}
}
if _, err := buffer.WriteTo(w); err != nil {
return err
}
return nil
}
func getDefaultGatewayIfaceName() (string, error) {
routes, err := netlink.NetworkGetRoutes()
if err != nil {
return "", err
}
for _, route := range routes {
if route.Default {
if route.Iface == nil {
return "", errors.New("found default route but could not determine interface")
}
return route.Iface.Name, nil
}
}
return "", errors.New("unable to find default route")
}