portscan.go 924 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package ipscan
  2. /*
  3. Port Scanner
  4. This module scan the given IP address and scan all the opened port
  5. */
  6. import (
  7. "fmt"
  8. "net"
  9. "sync"
  10. "time"
  11. )
  12. // OpenedPort holds information about an open port and its service type
  13. type OpenedPort struct {
  14. Port int
  15. IsTCP bool
  16. }
  17. // ScanPorts scans all the opened ports on a given host IP (both IPv4 and IPv6)
  18. func ScanPorts(host string) []*OpenedPort {
  19. var openPorts []*OpenedPort
  20. var wg sync.WaitGroup
  21. var mu sync.Mutex
  22. for port := 1; port <= 65535; port++ {
  23. wg.Add(1)
  24. go func(port int) {
  25. defer wg.Done()
  26. address := fmt.Sprintf("%s:%d", host, port)
  27. // Check TCP
  28. conn, err := net.DialTimeout("tcp", address, 5*time.Second)
  29. if err == nil {
  30. mu.Lock()
  31. openPorts = append(openPorts, &OpenedPort{Port: port, IsTCP: true})
  32. mu.Unlock()
  33. conn.Close()
  34. }
  35. }(port)
  36. }
  37. wg.Wait()
  38. return openPorts
  39. }