Created
June 1, 2024 02:47
-
-
Save tidwall/a98a697cc92bc1c8c80a40cd382265fc to your computer and use it in GitHub Desktop.
Port scanner in Go
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
package main | |
import ( | |
"fmt" | |
"net" | |
"sync" | |
"time" | |
) | |
func dial_port(host string, port int, wg *sync.WaitGroup) { | |
// Dial the port with a one second deadline | |
addr := fmt.Sprintf("%s:%d", host, port) | |
conn, err := net.DialTimeout("tcp", addr, time.Second) | |
if err != nil { | |
fmt.Printf("%-5d FAIL\t%s\n", port, err) | |
} else { | |
fmt.Printf("%-5d OK\n", port) | |
conn.Close() | |
} | |
// Notify the waitgroup that we are done. | |
wg.Done() | |
} | |
func main() { | |
host := "scanme.nmap.org" | |
ports := []int{22, 80, 8080, 443} | |
// Use a waitgroup to synchronize the coroutines | |
var wg sync.WaitGroup | |
// Dial all the ports | |
fmt.Printf("%s\n", host) | |
for i := 0; i < len(ports); i++ { | |
wg.Add(1) | |
go dial_port(host, ports[i], &wg) | |
} | |
// Wait for all coroutines to finish | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment