@@ -9,14 +9,50 @@ import (
99 "fmt"
1010 "net"
1111 "os"
12+ "sort"
1213 "strconv"
1314 "text/tabwriter"
1415)
1516
1617// TODO implement the following flags
17- // -r src | dst | src-port | dst-port | state : sort connections
1818// -N: display NAT box connection information (only valid with SNAT & DNAT)
1919
20+ type FlowSlice conntrack.FlowSlice
21+
22+ type SortBySource struct { FlowSlice }
23+ type SortByDestination struct { FlowSlice }
24+ type SortBySPort struct { FlowSlice }
25+ type SortByDPort struct { FlowSlice }
26+ type SortByState struct { FlowSlice }
27+
28+ func (flows FlowSlice ) Swap (i , j int ) {
29+ flows [i ], flows [j ] = flows [j ], flows [i ]
30+ }
31+
32+ func (flows FlowSlice ) Len () int {
33+ return len (flows )
34+ }
35+
36+ func (flows SortBySource ) Less (i , j int ) bool {
37+ return flows .FlowSlice [i ].Original .Source .String () < flows .FlowSlice [j ].Original .Source .String ()
38+ }
39+
40+ func (flows SortByDestination ) Less (i , j int ) bool {
41+ return flows .FlowSlice [i ].Original .Destination .String () < flows .FlowSlice [j ].Original .Destination .String ()
42+ }
43+
44+ func (flows SortBySPort ) Less (i , j int ) bool {
45+ return flows .FlowSlice [i ].Original .SPort < flows .FlowSlice [j ].Original .SPort
46+ }
47+
48+ func (flows SortByDPort ) Less (i , j int ) bool {
49+ return flows .FlowSlice [i ].Original .DPort < flows .FlowSlice [j ].Original .DPort
50+ }
51+
52+ func (flows SortByState ) Less (i , j int ) bool {
53+ return flows .FlowSlice [i ].State < flows .FlowSlice [j ].State
54+ }
55+
2056var Version = "0.1.0"
2157
2258var onlySNAT = flag .BoolP ("snat" , "S" , false , "Display only SNAT connections" )
@@ -29,6 +65,7 @@ var protocol = flag.StringP("protocol", "p", "", "Filter connections by protocol
2965var sourceHost = flag .StringP ("source" , "s" , "" , "Filter by source IP" )
3066var destinationHost = flag .StringP ("destination" , "d" , "" , "Filter by destination IP" )
3167var displayVersion = flag .BoolP ("version" , "v" , false , "Print version" )
68+ var sortBy = flag .StringP ("sort" , "r" , "src" , "Sort connections (src | dst | src-port | dst-port | state)" )
3269
3370func main () {
3471 flag .Parse ()
@@ -92,6 +129,19 @@ func main() {
92129 })
93130 }
94131
132+ switch * sortBy {
133+ case "src" :
134+ sort .Sort (SortBySource {FlowSlice (filteredFlows )})
135+ case "dst" :
136+ sort .Sort (SortByDestination {FlowSlice (filteredFlows )})
137+ case "src-port" :
138+ sort .Sort (SortBySPort {FlowSlice (filteredFlows )})
139+ case "dst-port" :
140+ sort .Sort (SortByDPort {FlowSlice (filteredFlows )})
141+ case "state" :
142+ sort .Sort (SortByState {FlowSlice (filteredFlows )})
143+ }
144+
95145 for _ , flow := range filteredFlows {
96146 sHostname := resolve (flow .Original .Source , * noResolve )
97147 dHostname := resolve (flow .Original .Destination , * noResolve )
0 commit comments