-
Notifications
You must be signed in to change notification settings - Fork 0
add a utility for finding all the TCP ports in listen (with the ability to exclude ports) #125
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jhaynie
wants to merge
3
commits into
main
Choose a base branch
from
network-ports
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| //go:build darwin | ||
|
|
||
| package network | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "bytes" | ||
| "fmt" | ||
| "os/exec" | ||
| "regexp" | ||
| "sort" | ||
| "strconv" | ||
| ) | ||
|
|
||
| // DetectListeningTCPPorts scans the system for TCP ports that are currently bound and listening. | ||
| // It returns a slice of port numbers, excluding any in the exclude list. | ||
| // Works on MacOS by running the lsof command. | ||
| func DetectListeningTCPPorts(exclude ...int) ([]int, error) { | ||
| excludeSet := make(map[int]struct{}) | ||
| for _, p := range exclude { | ||
| excludeSet[p] = struct{}{} | ||
| } | ||
|
|
||
| cmd := exec.Command("lsof", "-nP", "-iTCP", "-sTCP:LISTEN") | ||
| out, err := cmd.Output() | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to run lsof: %w", err) | ||
| } | ||
|
|
||
| scanner := bufio.NewScanner(bytes.NewReader(out)) | ||
| portPattern := regexp.MustCompile(`:(\d+)\s+\(LISTEN\)`) | ||
|
|
||
| ports := make(map[int]struct{}) | ||
|
|
||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| matches := portPattern.FindStringSubmatch(line) | ||
| if len(matches) != 2 { | ||
| continue | ||
| } | ||
| port, err := strconv.Atoi(matches[1]) | ||
| if err != nil { | ||
| continue | ||
| } | ||
| if _, excluded := excludeSet[port]; !excluded { | ||
| ports[port] = struct{}{} | ||
| } | ||
| } | ||
|
|
||
| if err := scanner.Err(); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Convert to sorted slice | ||
| var result []int | ||
| for p := range ports { | ||
| result = append(result, p) | ||
| } | ||
| sort.Ints(result) | ||
| return result, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| //go:build linux | ||
|
|
||
| package network | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "os" | ||
| "sort" | ||
| "strconv" | ||
| "strings" | ||
| ) | ||
|
|
||
| // DetectListeningTCPPorts scans the system for TCP ports that are currently bound and listening. | ||
| // It returns a slice of port numbers, excluding any in the exclude list. | ||
| // Works on Linux by reading /proc/net/tcp and /proc/net/tcp6. | ||
| func DetectListeningTCPPorts(exclude ...int) ([]int, error) { | ||
| excludeSet := make(map[int]struct{}) | ||
| for _, p := range exclude { | ||
| excludeSet[p] = struct{}{} | ||
| } | ||
|
|
||
| files := []string{"/proc/net/tcp", "/proc/net/tcp6"} | ||
| portSet := make(map[int]struct{}) | ||
|
|
||
| for _, path := range files { | ||
| f, err := os.Open(path) | ||
| if err != nil { | ||
| continue // skip if file doesn't exist or can't be read | ||
| } | ||
| defer f.Close() | ||
|
|
||
| scanner := bufio.NewScanner(f) | ||
| // Skip the header line | ||
| if scanner.Scan() { | ||
| for scanner.Scan() { | ||
| fields := strings.Fields(scanner.Text()) | ||
| if len(fields) < 4 { | ||
| continue | ||
| } | ||
|
|
||
| localAddr := fields[1] | ||
| state := fields[3] | ||
| if state != "0A" { // 0A means LISTEN | ||
| continue | ||
| } | ||
|
|
||
| // localAddr example: 0100007F:1F90 | ||
| parts := strings.Split(localAddr, ":") | ||
| if len(parts) != 2 { | ||
| continue | ||
| } | ||
|
|
||
| portHex := parts[1] | ||
| portDec, err := strconv.ParseInt(portHex, 16, 32) | ||
| if err != nil { | ||
| continue | ||
| } | ||
| port := int(portDec) | ||
|
|
||
| if _, excluded := excludeSet[port]; !excluded { | ||
| portSet[port] = struct{}{} | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| var ports []int | ||
| for p := range portSet { | ||
| ports = append(ports, p) | ||
| } | ||
| sort.Ints(ports) | ||
| return ports, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| package network | ||
|
|
||
| import ( | ||
| "net" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestDetectListeningTCPPorts(t *testing.T) { | ||
| ports, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
| assert.NotNil(t, ports) | ||
| assert.GreaterOrEqual(t, len(ports), 0) | ||
|
|
||
| if len(ports) > 1 { | ||
| for i := 1; i < len(ports); i++ { | ||
| assert.Greater(t, ports[i], ports[i-1], "ports should be sorted in ascending order") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsWithExclusion(t *testing.T) { | ||
| allPorts, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| if len(allPorts) == 0 { | ||
| t.Skip("no listening ports detected, skipping exclusion test") | ||
| } | ||
|
|
||
| portToExclude := allPorts[0] | ||
| filteredPorts, err := DetectListeningTCPPorts(portToExclude) | ||
| require.NoError(t, err) | ||
|
|
||
| for _, port := range filteredPorts { | ||
| assert.NotEqual(t, portToExclude, port, "excluded port should not be in result") | ||
| } | ||
| assert.Equal(t, len(allPorts)-1, len(filteredPorts), "should have one less port after exclusion") | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsWithMultipleExclusions(t *testing.T) { | ||
| allPorts, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| if len(allPorts) < 3 { | ||
| t.Skip("not enough listening ports detected, skipping multiple exclusion test") | ||
| } | ||
|
|
||
| excludePorts := []int{allPorts[0], allPorts[1], allPorts[2]} | ||
| filteredPorts, err := DetectListeningTCPPorts(excludePorts...) | ||
| require.NoError(t, err) | ||
|
|
||
| for _, port := range filteredPorts { | ||
| for _, excluded := range excludePorts { | ||
| assert.NotEqual(t, excluded, port, "excluded port should not be in result") | ||
| } | ||
| } | ||
| assert.Equal(t, len(allPorts)-len(excludePorts), len(filteredPorts), "should have three fewer ports after exclusion") | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsWithNonExistentExclusion(t *testing.T) { | ||
| allPorts, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| nonExistentPort := 65534 | ||
| filteredPorts, err := DetectListeningTCPPorts(nonExistentPort) | ||
| require.NoError(t, err) | ||
|
|
||
| assert.Equal(t, len(allPorts), len(filteredPorts), "excluding non-existent port should not change result") | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsWithActualListener(t *testing.T) { | ||
| listener, err := net.Listen("tcp", "127.0.0.1:0") | ||
| require.NoError(t, err) | ||
| defer listener.Close() | ||
|
|
||
| addr := listener.Addr().(*net.TCPAddr) | ||
| boundPort := addr.Port | ||
|
|
||
| ports, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| found := false | ||
| for _, port := range ports { | ||
| if port == boundPort { | ||
| found = true | ||
| break | ||
| } | ||
| } | ||
| assert.True(t, found, "should detect the port we just bound to") | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsWithActualListenerAndExclude(t *testing.T) { | ||
| listener, err := net.Listen("tcp", "127.0.0.1:0") | ||
| require.NoError(t, err) | ||
| defer listener.Close() | ||
|
|
||
| addr := listener.Addr().(*net.TCPAddr) | ||
| boundPort := addr.Port | ||
|
|
||
| ports, err := DetectListeningTCPPorts(boundPort) | ||
| require.NoError(t, err) | ||
|
|
||
| for _, port := range ports { | ||
| assert.NotEqual(t, boundPort, port, "excluded port should not appear even though it's listening") | ||
| } | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsNoDuplicates(t *testing.T) { | ||
| ports, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| seen := make(map[int]bool) | ||
| for _, port := range ports { | ||
| assert.False(t, seen[port], "port %d appears multiple times in result", port) | ||
| seen[port] = true | ||
| } | ||
| } | ||
|
|
||
| func TestDetectListeningTCPPortsValidRange(t *testing.T) { | ||
| ports, err := DetectListeningTCPPorts() | ||
| require.NoError(t, err) | ||
|
|
||
| for _, port := range ports { | ||
| assert.GreaterOrEqual(t, port, 1, "port should be >= 1") | ||
| assert.LessOrEqual(t, port, 65535, "port should be <= 65535") | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix resource leak: defer in loop.
The
defer f.Close()executes at function exit, not at the end of each loop iteration. If both/proc/net/tcpand/proc/net/tcp6exist, the first file remains open until the function returns.Apply this diff to close immediately after reading:
for _, path := range files { f, err := os.Open(path) if err != nil { continue // skip if file doesn't exist or can't be read } - defer f.Close() scanner := bufio.NewScanner(f) // Skip the header line if scanner.Scan() { for scanner.Scan() { fields := strings.Fields(scanner.Text()) if len(fields) < 4 { continue } localAddr := fields[1] state := fields[3] if state != "0A" { // 0A means LISTEN continue } // localAddr example: 0100007F:1F90 parts := strings.Split(localAddr, ":") if len(parts) != 2 { continue } portHex := parts[1] portDec, err := strconv.ParseInt(portHex, 16, 32) if err != nil { continue } port := int(portDec) if _, excluded := excludeSet[port]; !excluded { ports = append(ports, port) } } } + f.Close() }📝 Committable suggestion
🤖 Prompt for AI Agents