dongzhuange2625 2017-01-26 20:11
浏览 65
已采纳

遍历端口列表以连接Golang

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条回答 默认 最新

  • 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 (
        "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
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog