发布时间:2024-12-23 04:10:59
```go package main import ( "fmt" "net" ) func main() { port := "8080" listener, err := net.Listen("tcp", ":"+port) if err != nil { fmt.Printf("Port %s is already in use\n", port) return } defer listener.Close() fmt.Printf("Port %s is available\n", port) } ```
上述代码中,我们使用net包的Listen函数来尝试监听一个特定端口。如果端口已经被占用,那么调用Listen函数时会抛出错误。我们只需检查该错误,即可知道端口是否被占用。```go package main import ( "fmt" "os/exec" "strings" ) func main() { port := "8080" out, err := exec.Command("lsof", "-i", ":"+port).Output() if err != nil { fmt.Printf("Failed to execute command: %s\n", err) return } if len(strings.TrimSpace(string(out))) > 0 { fmt.Printf("Port %s is already in use\n", port) return } fmt.Printf("Port %s is available\n", port) } ```
上述代码中,我们使用了exec包的Command函数来执行"lsof -i :port"命令,该命令可以在Mac和Linux系统中列出指定端口的相关信息。如果命令输出不为空,则说明端口已经被占用。```go package main import ( "fmt" "net" ) func main() { port := "8080" listener, err := net.Listen("tcp", ":"+port) if err != nil { fmt.Printf("Port %s is already in use\n", port) return } defer listener.Close() fmt.Printf("Port %s is available\n", port) } ```
```go package main import ( "fmt" "os/exec" "strings" ) func main() { port := "8080" out, err := exec.Command("lsof", "-i", ":"+port).Output() if err != nil { fmt.Printf("Failed to execute command: %s\n", err) return } if len(strings.TrimSpace(string(out))) > 0 { fmt.Printf("Port %s is already in use\n", port) return } fmt.Printf("Port %s is available\n", port) } ```
以上是两种常用的检测端口占用的方法,开发者可以根据自己的需求选择适合的方法进行使用。