首頁  >  文章  >  後端開發  >  Golang TCP 連線有效,但 UDP 無效

Golang TCP 連線有效,但 UDP 無效

PHPz
PHPz轉載
2024-02-06 10:54:12388瀏覽

Golang TCP 连接有效,但 UDP 无效

問題內容

我正在透過 netcat 監聽 nc -lkp 1902

每當我建立 tcp 連線並嘗試傳送日誌時,它都會起作用

timeout := 30 * time.second
    conn, err := net.dialtimeout("tcp", "localhost:1902", timeout)
    if err != nil {
        panic("failed to connect to localhost:1902")
    }
    defer conn.close()

    f := log.ldate | log.lshortfile
    logger := log.new(conn, "example-", f)
    logger.println("this is a regular message1")
    logger.println("this is a regular message2")
    logger.println("this is a regular message3")
    logger.println("this is a regular message4")
    logger.println("this is a regular message5")
    logger.println("this is a regular message6")

輸出

example-2022/11/18 technique24.go:21: this is a regular message1
example-2022/11/18 technique24.go:22: this is a regular message2
example-2022/11/18 technique24.go:23: this is a regular message3
example-2022/11/18 technique24.go:24: this is a regular message4
example-2022/11/18 technique24.go:25: this is a regular message5
example-2022/11/18 technique24.go:26: this is a regular message6

但是每當我嘗試建立 udp 連接時它都不起作用,有人可以解釋為什麼我的記錄器上什麼也沒有得到嗎?

timeout := 30 * time.Second
    conn, err := net.DialTimeout("udp", "localhost:1902", timeout)
    if err != nil {
        panic("Failed to connect to localhost:1902")
    }
    defer conn.Close()

    f := log.Ldate | log.Lshortfile
    logger := log.New(conn, "example-", f)
    logger.Println("This is a regular message1")
    logger.Println("This is a regular message2")
    logger.Println("This is a regular message3")
    logger.Println("This is a regular message4")
    logger.Println("This is a regular message5")
    logger.Println("This is a regular message6")

想要製作一個小poc來通過udp發送日誌以減少積壓,嘗試首先建立tcp連接,它工作正常,但udp不起作用,有人可以解釋我必須做什麼才能使其工作嗎? p>

正確答案


除非另有指定,否則 Netcat 預設會建立 TCP 連線。對於 UDP 連接,您需要使用 netcat 的 -u 標誌。來自 netcat 手冊頁

#

-u 使用 UDP 取代預設的 TCP 選項。

因此,將偵聽器變更為 nc -luk 1902 應該可以解決 UDP 連線的問題。

以上是Golang TCP 連線有效,但 UDP 無效的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除