portScan.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 liuyuqi.gov@msn.cn.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "net"
  18. "os"
  19. "sync"
  20. "time"
  21. )
  22. func checkPort(ip net.IP, port int, wg *sync.WaitGroup) {
  23. tcpAddr := net.TCPAddr{
  24. IP: ip,
  25. Port: port,
  26. }
  27. ch := make(chan bool)
  28. timeout := make(chan bool)
  29. go func() {
  30. time.Sleep(3 * time.Second)
  31. timeout <- true
  32. }()
  33. go func() {
  34. conn, err := net.DialTCP("tcp", nil, &tcpAddr)
  35. ch <- true
  36. if err == nil {
  37. fmt.Printf("ip: %v port: %v \n", ip, port)
  38. defer func() {
  39. if conn != nil {
  40. e := conn.Close()
  41. if e != nil {
  42. fmt.Println(e)
  43. }
  44. }
  45. }()
  46. }
  47. }()
  48. select {
  49. case <-timeout:
  50. wg.Done()
  51. case <-ch:
  52. wg.Done()
  53. }
  54. }
  55. func checkIp(ip string) bool {
  56. if net.ParseIP(ip) == nil {
  57. fmt.Println("非法ip地址")
  58. return false
  59. } else {
  60. return true
  61. }
  62. }
  63. func main() {
  64. startTime := time.Now()
  65. wg := sync.WaitGroup{}
  66. wg.Add(65534)
  67. ip := os.Args[1]
  68. if checkIp(ip) {
  69. for port := 1; port <= 65534; port++ {
  70. go checkPort(net.ParseIP(ip), port, &wg)
  71. }
  72. }
  73. wg.Wait()
  74. endTime := time.Now()
  75. fmt.Printf("执行时间 %v", endTime.Sub(startTime))
  76. }