字符串和整数拼接问题 golang

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

String and integer concatenation issues golang

问题

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

package main

import (
	"fmt"
	"log"
	"net"
	"os"
)

func main() {

	callme()

}

func callme() {

	var status string
	getip := os.Args[1]
	getport := 0
	for i := 0; i < 10; i++ {
		getport += i

		data := getip + ":" + strconv.Itoa(getport)
		conn, err := net.Dial("tcp", data)
		if err != nil {
			log.Println("Connection error:", err)
			status = "Unreachable"
		} else {

			status = strconv.Itoa(getport) + " - " + "Open"
			defer conn.Close()
		}

		fmt.Println(status)

	}
}

我从用户那里获取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.

package main

import (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net&quot;
	&quot;os&quot;
)

func main() {

	callme()

}

func callme() {

	var status string
	getip := os.Args[1]
	getport := 0
	for i := 0; i &lt; 10; i++ {
		getport += i

		data := getip + &quot;:&quot; + getport
		conn, err := net.Dial(&quot;tcp&quot;, data)
		if err != nil {
			log.Println(&quot;Connection error:&quot;, err)
			status = &quot;Unreachable&quot;
		} else {

			status = getport + &quot; - &quot; + &quot;Open&quot;
			defer conn.Close()
		}

		fmt.Println(status)

	}
}

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:

确定