Last active
May 12, 2018 04:38
-
-
Save picatz/d1df0cd5575bbb419f315354263c050a to your computer and use it in GitHub Desktop.
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" | |
) | |
type TargetHost struct { | |
ip string | |
} | |
func checkPortOpen(ip string, port int, timeout time.Duration) bool { | |
conn, _ := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), timeout) | |
if conn == nil { | |
return false | |
} | |
conn.Close() | |
return true | |
} | |
func (t *TargetHost) AsyncFindOpenPorts(start, stop int) <-chan int { | |
ports := make(chan int) | |
seconds := 1 | |
timeout := (time.Duration(seconds) * time.Second) | |
wg := sync.WaitGroup{} | |
for port := start; port <= stop; port++ { | |
wg.Add(1) | |
go func(port int) { | |
defer wg.Done() | |
if checkPortOpen(t.ip, port, timeout) { | |
ports <- port | |
} | |
}(port) | |
} | |
go func() { | |
defer close(ports) | |
wg.Wait() | |
}() | |
return ports | |
} | |
func main() { | |
t := TargetHost{"127.0.0.1"} | |
for p := range t.AsyncFindOpenPorts(500, 2500) { | |
fmt.Println(p) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment