main
Raw Download raw file
 1package active
 2
 3import (
 4	"fmt"
 5
 6	"github.com/vishvananda/netlink"
 7)
 8
 9func Connections(port uint16) (int, error) {
10	sockets, err := netlink.SocketDiagTCP(netlink.FAMILY_V4)
11	if err != nil {
12		return 0, fmt.Errorf("failed to read active sockets: %w", err)
13	}
14	flows, err := netlink.ConntrackTableList(
15		netlink.ConntrackTable,
16		netlink.FAMILY_V4)
17	if err != nil {
18		return 0, fmt.Errorf("failed to read conntrack flows: %w", err)
19	}
20
21	activeConnections := 0
22	for _, s := range sockets {
23		if s.ID.DestinationPort == port {
24			activeConnections++
25		}
26	}
27
28	for _, f := range flows {
29		if f.Forward.DstPort == port {
30			activeConnections++
31		}
32	}
33	if activeConnections == 0 {
34		return 0, nil
35	}
36	return activeConnections, nil
37}