liuyuqi-dellpc 4 years ago
commit
5a8dc1122a
2 changed files with 73 additions and 0 deletions
  1. 6 0
      README.md
  2. 67 0
      portScan.go

+ 6 - 0
README.md

@@ -0,0 +1,6 @@
+## GoScanPort
+
+```
+go run portScan.go 39.156.69.79
+
+```

+ 67 - 0
portScan.go

@@ -0,0 +1,67 @@
+//端口扫描,扫描哪些端口在使用
+package main
+
+import (
+	"fmt"
+	"net"
+	"os"
+	"sync"
+	"time"
+)
+
+func checkPort(ip net.IP, port int, wg *sync.WaitGroup) {
+	tcpAddr := net.TCPAddr{
+		IP:   ip,
+		Port: port,
+	}
+	ch := make(chan bool)
+	timeout := make(chan bool)
+	go func() {
+		time.Sleep(3 * time.Second)
+		timeout <- true
+	}()
+	go func() {
+		conn, err := net.DialTCP("tcp", nil, &tcpAddr)
+		ch <- true
+		if err == nil {
+			fmt.Printf("ip: %v port: %v \n", ip, port)
+			defer func() {
+				if conn != nil {
+					e := conn.Close()
+					if e != nil {
+						fmt.Println(e)
+					}
+				}
+			}()
+		}
+	}()
+	select {
+	case <-timeout:
+		wg.Done()
+	case <-ch:
+		wg.Done()
+	}
+}
+func checkIp(ip string) bool {
+	if net.ParseIP(ip) == nil {
+		fmt.Println("非法ip地址")
+		return false
+	} else {
+		return true
+	}
+}
+func main() {
+
+	startTime := time.Now()
+	wg := sync.WaitGroup{}
+	wg.Add(65534)
+	ip := os.Args[1]
+	if checkIp(ip) {
+		for port := 1; port <= 65534; port++ {
+			go checkPort(net.ParseIP(ip), port, &wg)
+		}
+	}
+	wg.Wait()
+	endTime := time.Now()
+	fmt.Printf("执行时间 %v", endTime.Sub(startTime))
+}