Skip to content

Commit e402833

Browse files
committed
sort hosts and ports
closes #28
1 parent 00d4815 commit e402833

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

internal/scanner/shared/results.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package shared
22

33
import (
4+
"sort"
5+
46
"github.com/backendsystems/nibble/internal/ports/services"
57
)
68

@@ -19,9 +21,10 @@ type HostResult struct {
1921
Ports []PortInfo `json:"ports,omitempty"`
2022
}
2123

22-
// EnrichPorts fills in service names for ports that have no banner.
24+
// EnrichPorts fills in service names for ports that have no banner and sorts by port number.
2325
// This keeps the data layer consistent for both TUI and JSON output.
2426
func EnrichPorts(h *HostResult) {
27+
sort.Slice(h.Ports, func(i, j int) bool { return h.Ports[i].Port < h.Ports[j].Port })
2528
for i := range h.Ports {
2629
if h.Ports[i].Service == "" {
2730
if info := services.Lookup(h.Ports[i].Port); info != nil {

internal/tui/views/scan/actions.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package scanview
22

33
import (
44
"net"
5+
"sort"
56
"time"
67

78
"charm.land/bubbles/v2/stopwatch"
@@ -19,7 +20,24 @@ type ProgressMsg struct {
1920
type CompleteMsg struct{}
2021
type QuitMsg struct{}
2122

22-
// appendIfNew appends host to hosts only if no existing entry has the same IP.
23+
func sortHosts(hosts []shared.HostResult) {
24+
sort.Slice(hosts, func(i, j int) bool {
25+
a := net.ParseIP(hosts[i].IP).To4()
26+
b := net.ParseIP(hosts[j].IP).To4()
27+
if a == nil || b == nil {
28+
return hosts[i].IP < hosts[j].IP
29+
}
30+
for k := range a {
31+
if a[k] != b[k] {
32+
return a[k] < b[k]
33+
}
34+
}
35+
return false
36+
})
37+
}
38+
39+
// appendIfNew appends host to hosts only if no existing entry has the same IP,
40+
// keeping the slice sorted by IP.
2341
func appendIfNew(hosts []shared.HostResult, host *shared.HostResult) []shared.HostResult {
2442
if host == nil {
2543
return hosts
@@ -29,7 +47,9 @@ func appendIfNew(hosts []shared.HostResult, host *shared.HostResult) []shared.Ho
2947
return hosts
3048
}
3149
}
32-
return append(hosts, *host)
50+
hosts = append(hosts, *host)
51+
sortHosts(hosts)
52+
return hosts
3353
}
3454

3555
func ListenForProgress(progressChan <-chan shared.ProgressUpdate) tea.Cmd {
@@ -85,6 +105,7 @@ func prepareForExit(m Model, shouldPrint bool) Model {
85105
if len(m.FinalHosts) == 0 && len(m.FoundHosts) > 0 {
86106
m.FinalHosts = make([]shared.HostResult, len(m.FoundHosts))
87107
copy(m.FinalHosts, m.FoundHosts)
108+
sortHosts(m.FinalHosts)
88109
}
89110
m.FoundHosts = nil
90111
m.Results.SetContent("")

0 commit comments

Comments
 (0)