Reinaldo Saraiva
Reinaldo Saraiva

Reputation: 11

Troubleshooting NFTables Table Creation with Go

I've been working on a Go script that interacts with NFTables to create and manage firewall rules. However, I'm facing a persistent issue when attempting to create a new table. Despite trying various approaches and checking for common pitfalls (like table name conflicts and ensuring proper privileges), the script consistently fails to create a new table.

Here's the core part of my script:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/google/nftables"
)

func main() {
    conn, err := nftables.New()
    if err != nil {
        log.Fatalf("Error creating NFTables connection: %v", err)
    }

    // Attempting to create a new table with a unique name
    tableName := "test_nft_table"

    // Check if the table already exists
    tables, err := conn.ListTables()
    if err != nil {
        log.Fatalf("Error listing tables: %v", err)
    }
    exists := false
    for _, t := range tables {
        if t.Name == tableName {
            exists = true
            break
        }
    }

    if exists {
        fmt.Printf("Table '%s' already exists.\n", tableName)
    } else {
        // Create the table
        table := &nftables.Table{
            Family: nftables.TableFamilyIPv4,
            Name:   tableName,
        }
        if err := conn.AddTable(table); err != nil {
            log.Fatalf("Error adding table '%s': %v", tableName, err)
        }
        fmt.Printf("Table '%s' created successfully.\n", tableName)
    }

    if err := conn.Flush(); err != nil {
        log.Fatalf("Error applying changes: %v", err)
    }
}

The error message I receive is: Error adding table 'test_nft_table': &{test_nft_table 0 0 2}. This message is quite generic and doesn't provide much insight into what might be going wrong.

I've tried the following to diagnose and resolve the issue:

I would greatly appreciate any insights or suggestions you might have on what could be causing this issue or any additional diagnostic steps I could take.

Thank you in advance for your time and help!

Upvotes: 1

Views: 256

Answers (1)

yi yang
yi yang

Reputation: 66

conclusion: the successful return value of conn.AddTable() is not nil but instance of type *table.

replace

    if err := conn.AddTable(table); err != nil {

        log.Fatalf("Error adding table '%s': %v", tableName, err)

    }

with

conn.AddTable(table)

the table will be added successfully.


debug with dlv: enter image description here

Upvotes: 0

Related Questions