Skip to content
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

feat: add port scanner and related makefile #400

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pure-go-port-scanner/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.PHONY: run build clean

run:
go run .

build: clean
go build -o bin/scanner scanner.go

clean:
rm -rf ./bin/*
Binary file added pure-go-port-scanner/bin/scanner
Binary file not shown.
3 changes: 3 additions & 0 deletions pure-go-port-scanner/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module pure_go_port_scanner

go 1.23.1
60 changes: 60 additions & 0 deletions pure-go-port-scanner/scanner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"fmt"
"log"
"net"
"sync"
"time"
)

func scanPort(portNumber int) bool {
conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", portNumber))
if err != nil {
return false
}
defer conn.Close()
return true
}

func main() {
const MAX_PORT int = 65536
wg := sync.WaitGroup{}
outCh := make(chan int)
totalTime := float64(0)

log.Println("Starting Port Scan")
tx := time.Now()

for port := 1; port < int(MAX_PORT); port++ {
wg.Add(1)

// dial the port and report the status
go func() {
tx := time.Now()
if scanPort(port) {
outCh <- port
}
td := time.Since(tx)
totalTime += td.Seconds()
wg.Done()
}()
}

// wait for all port scans to complete
go func() {
wg.Wait()
outCh <- -1
}()

// this loop will check both channels and stop when the stopCh receives a signal
for p := range outCh {
if p == -1 {
td := time.Since(tx).Seconds()
avg := totalTime / float64(MAX_PORT)
log.Printf("!! Scanned %d ports in %f seconds (%f seconds per scan)\n", MAX_PORT, td, avg)
return
}
log.Printf("Open Port: %d", p)
}
}