在golang中遍历端口列表以进行连接性检查

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

Iterating through list of ports for connectivity in golang

问题

寻找一种通过特定端口迭代来检查主机之间连接性的方法。例如:

conn, err := net.Dial("tcp", "golang.org:80")
if err != nil {
    // 处理错误
}

我希望能够从某种类型的文件(如YAML或JSON)中读取所有输入,以便可以传入是UDP还是TCP端口,并通过文件中指定的不同端口号进行迭代,返回连接结果,并在完成检查最后一个端口后终止。我对GO语言还不熟悉,非常感谢任何帮助或建议。

英文:

Looking for a way to iterate through specific ports to check connectivity between hosts. For example

    conn, err := net.Dial("tcp", "golang.org:80")
if err != nil {
	// handle error

I am looking to make the input all be read from some type of file such as YAML or JSON, so it can pass in whether it is UDP or TCP port and go through the different port number specified in the file, return results of connection and terminate once it finishes checking the final port listed. I am new to GO and any help or suggestions would be greatly appreciated.

答案1

得分: 2

你可以使用os包来从文件中读取数据,然后使用json包将其解析为切片或映射等数据结构。然后遍历该数据结构来进行连接检查。

例如,如果你的文件名为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.Sprintf("%s:%d", host, p.Port))
        if err != nil {
            // 处理错误
        }
    }
}
英文:

You can use the os package to read from a file, and the json package to parse that into a data structure like a slice or map. Then iterate over that data structure to do the connectivity check.

For example, if your file is named ports.json and looks like

[
    {"port": 80, "protocol": "tcp"},
    {"port": 53, "protocol": "udp"}
]

The code that you're looking for looks something like

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
		}
	}
}

huangapple
  • 本文由 发表于 2017年1月27日 04:11:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41882111.html
匿名

发表评论

匿名网友

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

确定