github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgSys/iptable.go (about) 1 package kmgSys 2 3 import ( 4 "github.com/bronze1man/kmg/kmgCmd" 5 "strings" 6 ) 7 8 type IptableRule struct { 9 Table string // example: "nat" 10 Rule string // example: "-A PREROUTING -s 172.20.0.0/16 -p udp -m udp --dport 53 -j REDIRECT --to-ports 53" 11 } 12 13 func MustSetIptableRule(rule IptableRule) { 14 for _, thisRule := range MustGetIptableRuleList() { 15 if thisRule.Table == rule.Table && thisRule.Rule == rule.Rule { 16 return 17 } 18 } 19 // Another app is currently holding the xtables lock. Perhaps you want to use the -w option? 20 kmgCmd.MustRun("iptables -w -t " + rule.Table + " " + rule.Rule) 21 } 22 23 func MustGetIptableRuleList() []IptableRule { 24 content := kmgCmd.MustCombinedOutput("iptables-save") 25 return parseIptableSave(string(content)) 26 } 27 28 func parseIptableSave(content string) []IptableRule { 29 thisTable := "" 30 output := []IptableRule{} 31 for _, line := range strings.Split(content, "\n") { 32 line = strings.TrimSpace(line) 33 if line == "" { 34 continue 35 } 36 if line[0] == '#' || line[0] == ':' { 37 continue 38 } 39 if line[0] == '*' { 40 thisTable = line[1:] 41 continue 42 } 43 if line == "COMMIT" { 44 continue 45 } 46 output = append(output, IptableRule{ 47 Table: thisTable, 48 Rule: line, 49 }) 50 } 51 return output 52 }