-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloopback.go
83 lines (68 loc) · 1.85 KB
/
loopback.go
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
// Loopback device configuration
package main
import (
"errors"
"fmt"
"golang.org/x/exp/slices"
"log"
"net"
"os/exec"
"runtime"
)
var loopbackAliases = []string{}
func enableLoopbackAddr(addr string) error {
// First validate the IP address.
ip := net.ParseIP(addr)
if ip == nil {
return errors.New("Invalid IP address")
}
if slices.Contains(loopbackAliases, addr) {
// Already have this one.
return nil
}
_, subnet, _ := net.ParseCIDR("127.0.0.0/8")
if !subnet.Contains(ip) {
return errors.New("Invalid loopback IP address")
}
// Add the loopback alias or address.
if runtime.GOOS == "linux" {
// Nothing to do! Loopback aliases work automatically on Linux.
}
if runtime.GOOS == "darwin" {
rc := exec.Command("sh", "-c", fmt.Sprintf("ifconfig lo0 | grep 'inet %s '", addr)).Run()
if rc == nil {
return nil
}
// Add the loopback.
err := darwinSudoCommand(" to add loopback alias", []string{"ifconfig", "lo0", "alias", addr})
if err != nil {
return err
}
}
if runtime.GOOS == "windows" {
cmd := exec.Command("netsh", "interface", "ipv4", "add", "address", "Microsoft Loopback Adapter", addr, "255.0.0.0")
err := cmd.Run()
if err != nil {
return err
}
}
loopbackAliases = append(loopbackAliases, addr)
return nil
}
// Clean up resources allocated at runtime.
func loopbackCleanup() {
for _, addr := range loopbackAliases {
if runtime.GOOS == "darwin" {
fmt.Printf("removing lo0 alias %s\n", addr)
darwinSudoCommand(" to remove loopback alias", []string{"ifconfig", "lo0", "-alias", addr})
}
if runtime.GOOS == "windows" {
fmt.Printf("removing loopback address %s\n", addr)
cmd := exec.Command("netsh", "interface", "ipv4", "delete", "address", "Microsoft Loopback Adapter", addr)
err := cmd.Run()
if err != nil {
log.Println("Failed to remove loopback address:", err)
}
}
}
}