Advertisement
Guest User

Help with Channels

a guest
May 3rd, 2022
1,623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.98 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "net"
  6.     "time"
  7. )
  8.  
  9. func isPortOpen2(dest_host string, port int, out chan string) {
  10.     // defer close(out)
  11.     // If I do this, it closes the channel after the first execution of function which makes sense.
  12.     // But I dont do this, when I print the output I need to send ctrl c to exit the program.
  13.  
  14.  
  15.     timeout := time.Second * 1
  16.     target := fmt.Sprintf("%s:%d", dest_host, port)
  17.  
  18.     conn, err := net.DialTimeout("tcp", target, timeout)
  19.  
  20.     if err != nil {
  21.         out <- fmt.Sprintf("[%s]\t %s", "CLOSED", target)
  22.     }
  23.  
  24.     if conn != nil {
  25.         out <- fmt.Sprintf("[%s]\t %s", "OPEN", target)
  26.     }
  27. }
  28.  
  29. func main() {
  30.  
  31.     out := make(chan string)
  32.  
  33.     hosts := []string{"google.com", "reddit.com", "duckduckgo.com", "python.org"}
  34.     ports := []int{123, 43, 534, 325, 12, 443, 8080, 34, 5455, 23543, 9432, 843}
  35.  
  36.     for _, host := range hosts {
  37.         for _, port := range ports {
  38.             go isPortOpen2(host, port, out)
  39.         }
  40.     }
  41.  
  42.     for i := range out {
  43.         fmt.Println(i)
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement