Skip to content

Instantly share code, notes, and snippets.

@unakatsuo
Created April 11, 2018 13:22
Show Gist options
  • Save unakatsuo/e7085a723a2c56da878ebd2e5190d79f to your computer and use it in GitHub Desktop.
Save unakatsuo/e7085a723a2c56da878ebd2e5190d79f to your computer and use it in GitHub Desktop.
libiptc with Go
package main
/*
#cgo pkg-config: libiptc xtables
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <xtables.h>
#include <libiptc/libiptc.h>
static struct xtables_globals xtbl;
void init_xtables() {
xtables_init_all(&xtbl, NFPROTO_IPV4);
}
struct xtc_handle *create_xtc_handle()
{
struct xtc_handle *handle;
const char *tablename = "filter";
handle = iptc_init(tablename);
if (!handle) {
// try to insmod the module if iptc_init failed
xtables_load_ko(xtables_modprobe_program, false);
handle = iptc_init(tablename);
}
if (!handle) {
xtables_error(PARAMETER_PROBLEM, "unable to initialize "
"table '%s'\n", tablename);
return NULL;
}
return handle;
}
xt_chainlabel *to_xt_chainlabel(char *c) {
xt_chainlabel *l = malloc(sizeof(xt_chainlabel));
strncpy((char*)l, c, sizeof(xt_chainlabel));
return l;
}
int zero_entries(char *c, struct xtc_handle *h) {
xt_chainlabel l;
if( strlen(c) >= sizeof(xt_chainlabel) ) {
return -1;
}
strncpy((char*)l, c, sizeof(xt_chainlabel));
return iptc_zero_entries(l, h);
}
*/
import "C"
import (
"log"
"syscall"
"unsafe"
)
func iptc_strerror(err error) string {
eno, ok := err.(syscall.Errno)
if !ok {
panic("Unknown error type. syscall.Errno has to be passed")
}
return C.GoString(C.iptc_strerror(C.int(eno)))
}
func main() {
C.init_xtables()
hnd := C.create_xtc_handle()
if uintptr(unsafe.Pointer(hnd)) == uintptr(0) {
log.Fatal("Failed to create_handle")
}
defer C.iptc_free(hnd)
//var ret C.int
if ret, eno := C.zero_entries(C.CString("acct-10"), hnd); ret == C.int(0) {
log.Print("zero_entries: ", iptc_strerror(eno))
}
if ret, eno := C.iptc_commit(hnd); ret == C.int(0) {
log.Print("iptc_commit: ", iptc_strerror(eno))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment