diff --git a/iptables/iptables.go b/iptables/iptables.go index 4018ef6..e95929c 100644 --- a/iptables/iptables.go +++ b/iptables/iptables.go @@ -187,6 +187,12 @@ func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) er return ipt.run(cmd...) } +// Replace replaces rulespec to specified table/chain (in specified pos) +func (ipt *IPTables) Replace(table, chain string, pos int, rulespec ...string) error { + cmd := append([]string{"-t", table, "-R", chain, strconv.Itoa(pos)}, rulespec...) + return ipt.run(cmd...) +} + // InsertUnique acts like Insert except that it won't insert a duplicate (no matter the position in the chain) func (ipt *IPTables) InsertUnique(table, chain string, pos int, rulespec ...string) error { exists, err := ipt.Exists(table, chain, rulespec...) diff --git a/iptables/iptables_test.go b/iptables/iptables_test.go index 92ed271..cc2de33 100644 --- a/iptables/iptables_test.go +++ b/iptables/iptables_test.go @@ -309,6 +309,21 @@ func runRulesTests(t *testing.T, ipt *IPTables) { t.Fatalf("Delete failed: %v", err) } + err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Insert failed: %v", err) + } + + err = ipt.Replace("filter", chain, 1, "-s", subnet2, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Replace failed: %v", err) + } + + err = ipt.Delete("filter", chain, "-s", subnet2, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Delete failed: %v", err) + } + err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT") if err != nil { t.Fatalf("Append failed: %v", err)