使用go寫一個檢測tcpudp狀態的包

來源:互聯網
上載者:User

使用go寫一個檢測tcpudp狀態的包

因為要跟著 dockerpool 的基友寫 Docker 管理的程式,所以今年的目標是學習 go 語言。

看完 go 的入門教程,高深的代碼還看不懂,所以決定先嘗試寫一些平常可以用的東西,mac 底下的 nc 命令可以檢測很多東西,但是用著不習慣,所以決定寫一個 check tcp udp 的包。

package mainimport (    "flag"    "fmt"    "net")const version = "0.1.0"var Input_protocol = flag.String("p", "tcp", "The protocol you want to check")func tcp(url string) int {    _, err := net.Dial("tcp", url)    if err != nil {        fmt.Println(err)        return 0    } else {        return 1    }}func udp(url string) int {    _, err := net.Dial("udp", url)    if err != nil {        fmt.Println(err)        return 0    } else {        return 1    }}func main() {    flag.Parse()    if flag.NArg() < 1 {        useage := "使用樣本: check -p tcp 192.168.7.26:22 或者 check -p udp 192.168.7.23:123 "        fmt.Println(useage)        return    }    p := *Input_protocol    switch {    case p == "tcp":        r := tcp(flag.Args()[0])        fmt.Println(r)    case p == "udp":        r := udp(flag.Args()[0])        fmt.Println(r)    }}

go build go install 之後,就可以再命令列中使用了。

$ go build$ go install$ check使用樣本: check -p tcp 192.168.7.26:22 或者 check -p udp 192.168.7.23:123$ check -p tcp www.sina.com:801$ check -p tcp www.sina.com:88dial tcp 61.172.201.20:88: connection refused0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.