-
Notifications
You must be signed in to change notification settings - Fork 318
/
iptables.go
44 lines (34 loc) · 974 Bytes
/
iptables.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
package iptables
import (
"errors"
"net"
"strings"
"github.com/coreos/go-iptables/iptables"
)
// AddRule adds the required rule to the host's nat table.
func AddRule(appPort, metadataAddress, hostInterface, hostIP string) error {
if err := checkInterfaceExists(hostInterface); err != nil {
return err
}
if hostIP == "" {
return errors.New("--host-ip must be set")
}
ipt, err := iptables.New()
if err != nil {
return err
}
return ipt.AppendUnique(
"nat", "PREROUTING", "-p", "tcp", "-d", metadataAddress, "--dport", "80",
"-j", "DNAT", "--to-destination", hostIP+":"+appPort, "-i", hostInterface,
)
}
// checkInterfaceExists validates the interface passed exists for the given system.
// checkInterfaceExists ignores wildcard networks.
func checkInterfaceExists(hostInterface string) error {
if strings.Contains(hostInterface, "+") {
// wildcard networks ignored
return nil
}
_, err := net.InterfaceByName(hostInterface)
return err
}