超越 “Hello World”(4)

行108-132是运行TCP/IP侦听器的主函数。行109使Go运行环境使用所有物理可用的CPU。

108    func main() {
  109      runtime.GOMAXPROCS(runtime.NumCPU())
  110      flag.Parse()
  111      if flag.NFlag() != 3 {
  112        fmt.Printf("usage: gotcpspy -host target_host -port target_port
                -listen_post=local_port\n")
  113        flag.PrintDefaults()
  114        os.Exit(1)
  115      }
  116      target := net.JoinHostPort(*host, *port)
  117      fmt.Printf("Start listening on port %s and
              forwarding data to %s\n",
              *listen_port, target)
  118      ln, err := net.Listen("tcp", ":"+*listen_port)
  119      if err != nil {
  120        fmt.Printf("Unable to start listener, %v\n", err)
  121        os.Exit(1)
  122      }
  123      conn_n := 1
  124      for {
  125        if conn, err := ln.Accept(); err == nil {
  126          go process_connection(conn, conn_n, target)
  127          conn_n += 1
  128        } else {
  129          fmt.Printf("Accept failed, %v\n", err)
  130        }
  131      }
  132    }

就这些,只有132行。请注意:程序仅使用了Go语言自身的标准库。

现在准备运行:

go run gotcpspy.go -host pop.yandex.ru -port 110 -local_port 8080

输出应为:

Start listening on port 8080 and forwarding data to pop.yandex.ru:110

然后在另一个窗口运行:

telnet localhost 8080

然后回车,比如:USER  test  [ENTER]  和 PASS  none  [ENTER]。三个日志文件将被创建(当你运行时间戳会不同)。

双向十六进制导出日志文件  log-2012.04.20-19.55.17-0001-192.168.1.41 -49544-213.180.204.37-110.log:

Connected to pop.yandex.ru:110 at 2012.04.20-19.55.17
  Received (#0, 00000000) 38 bytes from 192.168.1.41-49544
  00000000  2b 4f 4b 20 50 4f 50 20  59 61 21 20 76 31 2e 30
    |+OK POP Ya! v1.0|
  00000010  2e 30 6e 61 40 32 36 20  48 74 6a 4a 69 74 63 50
    |.0na@26 HtjJitcP|
  00000020  52 75 51 31 0d 0a
    |RuQ1..|
  Sent (#0) to [--1]-8080
  Received (#0, 00000000) 11 bytes from [--1]-8080
  00000000  55 53 45 52 20 74 65 73  74 0d 0a
    |USER test..|
  Sent (#0) to 192.168.1.41-49544
  Received (#1, 00000026) 23 bytes from 192.168.1.41-49544
  00000000  2b 4f 4b 20 70 61 73 73  77 6f 72 64 2c 20 70 6c
    |+OK password, pl|
  00000010  65 61 73 65 2e 0d 0a
    |ease...|
  Sent (#1) to [--1]-8080
  Received (#1, 0000000B) 11 bytes from [--1]-8080
  00000000  50 41 53 53 20 6e 6f 6e  65 0d 0a
    |PASS none..|
  Sent (#1) to 192.168.1.41-49544
  Received (#2, 0000003D) 72 bytes from 192.168.1.41-49544
  00000000  2d 45 52 52 20 5b 41 55  54 48 5d 20 6c 6f 67 69
    |-ERR [AUTH] logi|
  00000010  6e 20 66 61 69 6c 75 72  65 20 6f 72 20 50 4f 50
    |n failure or POP|
  00000020  33 20 64 69 73 61 62 6c  65 64 2c 20 74 72 79 20
    |3 disabled, try |
  00000030  6c 61 74 65 72 2e 20 73  63 3d 48 74 6a 4a 69 74
    |later. sc=HtjJit|
  00000040  63 50 52 75 51 31 0d 0a
    |cPRuQ1..|
  Sent (#2) to [--1]-8080
  Disconnected from 192.168.1.41-49544
  Disconnected from [--1]-8080
  Finished at 2012.04.20-19.55.17, duration 5.253979s

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/901c8d2d20942b7d88e3cd2a380cd535.html