inetdiag_test.go 1.8 KB

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