寻找一种方法来遍历特定端口以检查主机之间的连接。例如
conn, err := net.Dial("tcp", "golang.org:80")
if err != nil {
// handle error
我希望让输入全部从某种类型的文件(如 YAML 或 JSON)中读取,因此它可以传入 UDP 或 TCP 端口并通过文件中指定的不同端口号,返回结果连接并在完成检查列出的最终端口后终止。我是 GO 的新手,非常感谢任何帮助或建议。
最佳答案
您可以使用 os
从文件中读取的包,以及 json
包将其解析为数据结构,如 slice 或映射。然后迭代该数据结构以进行连接检查。
例如,如果您的文件名为 ports.json
并且看起来像
[
{"port": 80, "protocol": "tcp"},
{"port": 53, "protocol": "udp"}
]
您要查找的代码类似于
package main
import (
"encoding/json"
"fmt"
"net"
"os"
)
type portDef struct {
Port int `json:"port"`
Protocol string `json:"protocol"`
}
func main() {
host := "golang.org"
file, err := os.Open("ports.json")
if err != nil {
panic(err)
}
defer file.Close()
ports := []portDef{}
err = json.NewDecoder(file).Decode(&ports)
if err != nil {
panic(err)
}
for _, p := range ports {
_, err := net.Dial(p.Protocol, fmt.Sprint("%s:%d", host, p.Port))
if err != nil {
// handle error
}
}
}
关于go - 遍历 golang 中连接的端口列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882111/