2017-01-26 20:11
浏览 50


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

    conn, err := net.Dial("tcp", "")
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.

图片转代码服务由CSDN问答提供 功能建议

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

  conn,err:= net.Dial(“ tcp”,“")
if err!= nil {

我希望从所有类型的文件(例如YAML或JSON)读取输入,因此无论是UDP还是TCP端口,它都可以传递 并检查文件中指定的其他端口号,返回连接结果,并在检查完最后一个端口后终止。 我是GO的新手,任何帮助或建议都将不胜感激。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpbvpgvrhwxen3222 2017-01-26 22:47

    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 (
    type portDef struct {
        Port     int    `json:"port"`
        Protocol string `json:"protocol"`
    func main() {
        host := ""
        file, err := os.Open("ports.json")
        if err != nil {
        defer file.Close()
        ports := []portDef{}
        err = json.NewDecoder(file).Decode(&ports)
        if err != nil {
        for _, p := range ports {
            _, err := net.Dial(p.Protocol, fmt.Sprint("%s:%d", host, p.Port))
            if err != nil {
                // handle error
    打赏 评论

相关推荐 更多相似问题