github.com/elastic/gosigar@v0.14.3/sys/linux/inetdiag_test.go (about)

     1  // +build linux
     2  
     3  package linux
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/hex"
     8  	"io/ioutil"
     9  	"syscall"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  // TestParseInetDiagMsgs reads netlink messages stored in a file (these can be
    16  // captured with ss -diag <file>).
    17  func TestParseInetDiagMsgs(t *testing.T) {
    18  	data, err := ioutil.ReadFile("testdata/inet-dump-rhel6-2.6.32-504.3.3.el6.x86_64.bin")
    19  	if err != nil {
    20  		t.Fatal(err)
    21  	}
    22  
    23  	t.Log("Netlink data length: ", len(data))
    24  	netlinkMsgs, err := syscall.ParseNetlinkMessage(data)
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  
    29  	t.Logf("Parsed %d netlink messages", len(netlinkMsgs))
    30  	done := false
    31  	for _, m := range netlinkMsgs {
    32  		if m.Header.Type == syscall.NLMSG_DONE {
    33  			done = true
    34  			break
    35  		}
    36  
    37  		inetDiagMsg, err := ParseInetDiagMsg(m.Data)
    38  		if err != nil {
    39  			t.Fatal("parse error", err)
    40  		}
    41  
    42  		if inetDiagMsg.DstPort() == 0 {
    43  			assert.EqualValues(t, TCP_LISTEN, inetDiagMsg.State)
    44  		} else {
    45  			assert.EqualValues(t, TCP_ESTABLISHED, inetDiagMsg.State)
    46  		}
    47  	}
    48  
    49  	assert.True(t, done, "missing NLMSG_DONE message")
    50  }
    51  
    52  // TestNetlinkInetDiag sends a inet_diag_req to the kernel, checks for errors,
    53  // and inspects the responses based on some invariant rules.
    54  func TestNetlinkInetDiag(t *testing.T) {
    55  	req := NewInetDiagReq()
    56  	req.Header.Seq = 12345
    57  
    58  	dump := new(bytes.Buffer)
    59  	msgs, err := NetlinkInetDiagWithBuf(req, nil, dump)
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	t.Logf("Received %d messages decoded from %d bytes", len(msgs), dump.Len())
    65  	for _, m := range msgs {
    66  		if m.Family != uint8(AF_INET) && m.Family != uint8(AF_INET6) {
    67  			t.Errorf("invalid Family (%v)", m.Family)
    68  		}
    69  
    70  		if m.DstPort() == 0 {
    71  			assert.True(t, m.DstIP().IsUnspecified(), "dport is 0, dst ip should be unspecified")
    72  			assert.EqualValues(t, m.State, TCP_LISTEN)
    73  		}
    74  	}
    75  
    76  	if t.Failed() {
    77  		t.Log("Raw newlink response:\n", hex.Dump(dump.Bytes()))
    78  	}
    79  }