第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

這種恐慌的原因是什么?

這種恐慌的原因是什么?

Go
青春有我 2022-07-25 11:17:35
為了練習(xí)一些基本概念,我正在編寫一個(gè)簡(jiǎn)單的端口掃描器。然而,當(dāng)嘗試實(shí)現(xiàn) goroutines 時(shí),程序會(huì)出現(xiàn)恐慌,并且出現(xiàn)分段錯(cuò)誤:Scanning ports{Port:139 State:Open}{Port:135 State:Open}{Port:136 State:Closed}{Port:131 State:Closed}{Port:131 State:Open}{Port:134 State:Closed}{Port:134 State:Open}panic: runtime error: invalid memory address or nil pointer dereference[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]goroutine 20 [running]:main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x83)        /home/athos/Projects/go-tutorial/scanner.go:33 +0x1eacreated by main.main        /home/athos/Projects/go-tutorial/scanner.go:41 +0xf1panic: runtime error: invalid memory address or nil pointer dereference[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]goroutine 23 [running]:main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x86)        /home/athos/Projects/go-tutorial/scanner.go:33 +0x1eacreated by main.main        /home/athos/Projects/go-tutorial/scanner.go:41 +0xf1exit status 2這是我的代碼:package mainimport (    "fmt"    "net"    "strconv"    "sync"    "time")var wg sync.WaitGrouptype scanResult struct {    Port  int    State string}func scanPort(protocol, hostname string, port int) {    defer wg.Done()    result := scanResult{Port: port}    socket := hostname + ":" + strconv.Itoa(port)    conn, err := net.DialTimeout(protocol, socket, 2*time.Second)    if err != nil {        result.State = "Closed"        fmt.Printf("%+v\n", result)    }    result.State = "Open"    fmt.Printf("%+v\n", result)    // Defers: FILO data structure    defer conn.Close()}func main() {    fmt.Println("Scanning ports")    for i := 130; i <= 145; i++ {        wg.Add(1)        go scanPort("tcp", "192.168.200.103", i)    }    // Wait for goroutines to complete    wg.Wait()}誰(shuí)能幫我看看我做錯(cuò)了什么?
查看完整描述

1 回答

?
開心每一天1111

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊

net.DialTimeout()返回連接和錯(cuò)誤,您正確檢查錯(cuò)誤是否不是nil,但即使有錯(cuò)誤,您只需打印并繼續(xù)。


如果存在非nil錯(cuò)誤,則不應(yīng)(絕不能)使用返回的連接,因?yàn)樗赡苁莕il無(wú)效值。如果有錯(cuò)誤,檢查/打印并返回,不要嘗試使用conn.


所以簡(jiǎn)單地返回:


if err != nil {

    result.State = "Closed"

    fmt.Printf("%+v\n", result)

    return

}

此外,如果沒有錯(cuò)誤,您可以“安排”立即關(guān)閉連接,延遲。defer如果您在函數(shù)中關(guān)閉連接的最后一件事,則使用毫無(wú)意義。


所以它應(yīng)該是這樣的:


conn, err := net.DialTimeout(protocol, socket, 2*time.Second)


if err != nil {

    result.State = "Closed"

    fmt.Printf("%+v\n", result)

    return

}


defer conn.Close()


result.State = "Open"

fmt.Printf("%+v\n", result)


查看完整回答
反對(duì) 回復(fù) 2022-07-25
  • 1 回答
  • 0 關(guān)注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)