This is a creation in Article, where the information may have evolved or changed.
Previous words
Recently obsessed with the emerging language of Golang, because it is a strongly typed, compiled language that can be compiled directly into a binary execution file of three platforms that can be run directly without the need for other dependent environments. And Golang's unique goroutine makes multithreaded tasks as simple as new objects.
With the curiosity to learn to understand Golang, I tried to write a port scanner.
The GitHub Project link is as follows, and more utilities I will add slowly.
Https://github.com/pwcong/go-tools
Source
Package Mainimport ("Flag" "FMT" "NET" "OS" "RegExp" "StrConv" "Strings" "Sync") var port intvar p Ortrange stringvar parallelcounts intfunc init () {flag. Intvar (&port, "P", +, "port") flag. Stringvar (&portrange, "R", "", "range ports. Format is <from>~<to>. eg. 100~200 ") flag. Intvar (¶llelcounts, "n", 1, "parallel Counts")//Modify message flag. Usage = func () {fmt. fprintf (OS. Stderr, "\nusage:%s [Options] <ip>\n\noptions:\n\n", OS. Args[0]) flag. Printdefaults ()} flag. Parse ()}func printopeningport (port int) {FMT. PRINTLN ("Port" + StrConv. Itoa (Port) + "is opening")}func Checkport (IP net. IP, Port INT, WG *sync. Waitgroup, Parallelchan *chan int) {defer WG. Done () Tcpaddr: = Net. tcpaddr{Ip:ip, Port:port,} conn, err: = Net. DIALTCP ("TCP", nil, &tcpaddr) if Err = = Nil {printopeningport (port) Conn. Close ()} <-*parallelchan}func main () {argS: = flag. Args () If Len (args)! = 1 {flag. Usage ()} else {IP: = net. PARSEIP (flag. ARG (0))//For the Coprocessor task control WG: = Sync. waitgroup{} if Portrange! = "" {matched, _: = RegExp. Match (' ^\d+~\d+$ ', []byte (Portrange)) if!matched {flag. Usage ()} else {portsecs: = strings. Split (Portrange, "~") Startport, err1: = StrConv. Atoi (Portsecs[0]) endport, err2: = StrConv. Atoi (portsecs[1]) if err1! = Nil | | Err2! = Nil | | Startport < 1 | | Endport < 2 | | Endport <= Startport | | Parallelcounts < 1 {flag. Usage ()} else {WG. ADD (Endport-startport + 1)//For controlling the number of threads Parallelchan: = Make (chan int, parallelcount s) for I: = Startport; I <= Endport; i++ {Parallelchan <-1 go checkport (IP, I, &wg, ¶llelchan)} WG. Wait ()}}} else {WG. ADD (1) Parallelchan: = make (chan int) go func () {Parallelchan <-1} () Go Checkport (IP, port, &WG, ¶llelchan) WG. Wait ()}}}
Run results
- Execute
go build ./main.go
, generate binary file
Run the binary file with the following results:
$ port-scanner.exeUsage: E:\Program Files\GoPath\bin\port-scanner.exe [Options] <IP>Options: -n int parallel counts (default 1) -p int port (default 80) -r string range ports. format is <from>~<to>. eg. 100~200$ port-scanner.exe -p 80 127.0.0.1port 80 is opening$ port-scanner.exe -r 1~100 -n 50 127.0.0.1port 80 is opening