golang查找端口號占用的進程號


golang官方包:

https://studygolang.com/pkgdoc

os

支持獲取當前進程pid並kill、但是僅僅限於獲取當前進程pid

FindProcess().Kill()
os.Getpid()

基礎用法;但是卻沒有提供依據端口號獲取對應的pid,所以還是執行shell指令對結果集進行過濾獲取pid

// 獲取8299端口對應進程號並kill
processInfo := exec.Command("/bin/sh", "-c",`lsof -i:8299 | awk '{print $2}' | awk  'NR==2{print}'`)
if pid, err := processInfo.Output(); err != nil {
    fmt.Println(err.Error())
}else{
    fmt.Println(string(pid))
    processExit := exec.Command("/bin/sh", "-c",`kill `+string(pid))
    if _, err := processExit.Output(); err != nil {
        fmt.Println(err.Error())
    }
}

and

// 傳入查詢的端口號
// 返回端口號對應的進程PID,若沒有找到相關進程,返回-1
func portInUse(portNumber int) int {
    res := -1
    var outBytes bytes.Buffer
    cmdStr := fmt.Sprintf("netstat -ano -p tcp | findstr %d", portNumber)
    cmd := exec.Command("cmd", "/c", cmdStr)
    cmd.Stdout = &outBytes
    cmd.Run()
    resStr := outBytes.String()
    r := regexp.MustCompile(`\s\d+\s`).FindAllString(resStr, -1)
    if len(r) > 0 {
        pid, err := strconv.Atoi(strings.TrimSpace(r[0]))
        if err != nil {
            res = -1
        } else {
            res = pid
        }
    }
    return res
}

端口檢測:

func ScanPort(protocol string, hostname string, port int) bool {
 fmt.Printf("scanning port %d \n", port)
 p := strconv.Itoa(port)
 addr := net.JoinHostPort(hostname, p)
 conn, err := net.DialTimeout(protocol, addr, 3*time.Second)
 if err != nil {
 return false
 }
 defer conn.Close()
 return true
}

參考博客:

https://www.jb51.net/article/208384.htm

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM