Created
May 30, 2020 03:18
-
-
Save rochacon/2291d7f41400b3ce8cc2d47085c27fcc to your computer and use it in GitHub Desktop.
portscan a cidr block port
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 ( | |
"flag" | |
"fmt" | |
"log" | |
"net" | |
"os" | |
"sync" | |
"time" | |
) | |
func main() { | |
concurrency := flag.Int("c", 1, "concurrency") | |
timeoutSeconds := flag.Int("t", 100, "Connection timeout in milliseconds") | |
verbose := flag.Bool("v", false, "verbose") | |
flag.Parse() | |
if flag.NArg() != 2 { | |
fmt.Println("Usage: portscan <cidr>/24 <port>") | |
fmt.Println("Example: portscan 192.168.0.0/24 <port>") | |
os.Exit(1) | |
} | |
cidr := flag.Arg(0) | |
port := flag.Arg(1) | |
timeout := time.Duration(*timeoutSeconds) * time.Millisecond | |
ip, ipnet, err := net.ParseCIDR(cidr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
ips := make(chan string) | |
wg := &sync.WaitGroup{} | |
for x := 0; x < *concurrency; x++ { | |
wg.Add(1) | |
go worker(x, ips, port, timeout, *verbose, wg) | |
} | |
for i := ip.Mask(ipnet.Mask); ipnet.Contains(i); inc(i) { | |
if *verbose { | |
log.Printf("ips <- %s", i) | |
} | |
ips <- i.String() | |
} | |
if *verbose { | |
log.Printf("close(ips)") | |
} | |
close(ips) | |
wg.Wait() | |
} | |
func worker(x int, ips <-chan string, port string, timeout time.Duration, verbose bool, wg *sync.WaitGroup) { | |
defer wg.Done() | |
if verbose { | |
log.Printf("[%d] waiting for ips", x) | |
} | |
var err error | |
for ip := range ips { | |
addr := ip + ":" + port | |
if verbose { | |
log.Printf("ping(%s, %s)", addr, timeout) | |
} | |
err = ping(addr, timeout) | |
if err == nil { | |
log.Println("Connection successful:", addr) | |
} | |
} | |
} | |
func ping(addr string, timeout time.Duration) error { | |
conn, err := net.DialTimeout("tcp", addr, timeout) | |
if err == nil { | |
conn.Close() | |
} | |
return err | |
} | |
func inc(ip net.IP) { | |
for j := len(ip) - 1; j >= 0; j-- { | |
ip[j]++ | |
if ip[j] > 0 { | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment