字符串和整数拼接问题 golang

huangapple go评论98阅读模式
英文:

String and integer concatenation issues golang

问题

我正在尝试用Go语言编写一个端口扫描器,但由于我对此不太熟悉,所以遇到了一些问题。以下是我目前编写的代码:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "os"
  7. )
  8. func main() {
  9. callme()
  10. }
  11. func callme() {
  12. var status string
  13. getip := os.Args[1]
  14. getport := 0
  15. for i := 0; i < 10; i++ {
  16. getport += i
  17. data := getip + ":" + strconv.Itoa(getport)
  18. conn, err := net.Dial("tcp", data)
  19. if err != nil {
  20. log.Println("Connection error:", err)
  21. status = "Unreachable"
  22. } else {
  23. status = strconv.Itoa(getport) + " - " + "Open"
  24. defer conn.Close()
  25. }
  26. fmt.Println(status)
  27. }
  28. }

我从用户那里获取IP作为命令行参数,然后想要扫描该IP上的所有端口。由于net.Dial函数需要以"ip:port"的格式提供数据,我有点困惑如何每次连接字符串和整数。有人可以帮助我实现这个吗?

英文:

I am trying to write a port scanner in Go, i am facing few problems since i am new to this. Below is the code i have written till now.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;log&quot;
  5. &quot;net&quot;
  6. &quot;os&quot;
  7. )
  8. func main() {
  9. callme()
  10. }
  11. func callme() {
  12. var status string
  13. getip := os.Args[1]
  14. getport := 0
  15. for i := 0; i &lt; 10; i++ {
  16. getport += i
  17. data := getip + &quot;:&quot; + getport
  18. conn, err := net.Dial(&quot;tcp&quot;, data)
  19. if err != nil {
  20. log.Println(&quot;Connection error:&quot;, err)
  21. status = &quot;Unreachable&quot;
  22. } else {
  23. status = getport + &quot; - &quot; + &quot;Open&quot;
  24. defer conn.Close()
  25. }
  26. fmt.Println(status)
  27. }
  28. }

I take ip from user as a command line arg, and then want to scan all ports on this ip. Since the net.Dial function needs data in a format like "ip:port" i am kinda confused how to concat string and int each time. Can any1 help me achieve this ?

答案1

得分: 9

一种可能性是使用strconv.Itoa(getport)int转换为string。另一种可能性是格式化字符串,例如fmt.Sprintf("%s:%d", getip, getport)fmt.Sprintf("%d - Open", getport)

英文:

One possibility is using strconv.Itoa(getport) to convert the int into a string. Another possibility is formatting the string, as in fmt.Sprintf(&quot;%s:%d&quot;, getip, getport) or fmt.Sprintf(&quot;%d - Open&quot;, getport).

huangapple
  • 本文由 发表于 2016年11月17日 03:58:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40641194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定