亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 檢查 tcp 端口打開

golang 檢查 tcp 端口打開

Go
POPMUISE 2023-06-19 17:09:38
我需要檢查遠程地址是否打開了特定的 TCP 端口。為此,我選擇使用 golang。到目前為止,這是我的嘗試:func raw_connect(host string, ports []string) {  for _, port := range ports {     timeout := time.Second     conn, err := net.DialTimeout("tcp", host + ":" + port, timeout)     if err != nil {        _, err_msg := err.Error()[0], err.Error()[5:]        fmt.Println(err_msg)     } else {        msg, _, err := bufio.NewReader(conn).ReadLine()        if err != nil {           if err == io.EOF {              fmt.Print(host + " " + port + " - Open!\n")           }        } else {           fmt.Print(host + " " + port + " - " + string(msg))        }        conn.Close()     }   } }當應用程序(例如 SSH)首先返回一個字符串時,這對于 TCP 端口工作得很好,我讀取它并立即打印它。但是,當 TCP 以上的應用程序首先等待來自客戶端的命令(例如 HTTP)時,就會出現超時 (if err == io.EOF子句)。這個超時時間很長。我需要立即知道端口是否打開。是否有更適合此目的的技術?
查看完整描述

2 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

要檢查端口,您可以檢查連接是否成功。例如:


func raw_connect(host string, ports []string) {

    for _, port := range ports {

        timeout := time.Second

        conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)

        if err != nil {

            fmt.Println("Connecting error:", err)

        }

        if conn != nil {

            defer conn.Close()

            fmt.Println("Opened", net.JoinHostPort(host, port))

        }

    }

}


查看完整回答
反對 回復 2023-06-19
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

檢查多個端口示例


func tcpGather(ip string, ports []string) map[string]string {

    // check emqx 1883, 8083 port


    results := make(map[string]string)

    for _, port := range ports {

        address := net.JoinHostPort(ip, port)

        // 3 second timeout

        conn, err := net.DialTimeout("tcp", address, 3*time.Second)

        if err != nil {

            results[port] = "failed"

            // todo log handler

        } else {

            if conn != nil {

                results[port] = "success"

                _ = conn.Close()

            } else {

                results[port] = "failed"

            }

        }

    }

    return results

}


查看完整回答
反對 回復 2023-06-19
  • 2 回答
  • 0 關注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號