代码
package mainimport ("fmt""log""net""os/exec""strconv""strings"
)func getSelect(beign int, end int) int {var num intfor {_, err := fmt.Scan(&num)if err != nil {fmt.Println("输入错误,请重新输入!")continue}if num < beign || num > end {fmt.Println("输入不在指定范围(1-10)之内,请重新输入!")continue}break}return num
}func main() {for {var port intfor {fmt.Print("请输入要检测的端口号:")_, err := fmt.Scanln(&port)if err != nil {fmt.Println("输入错误,请重新输入!")continue}break}// 检测端口是否被占用if isPortInUse(port) {fmt.Printf("端口号:%d 该端口号已经被占用\n", port)fmt.Print("请选择是否停用(1.是 2.否):")if getSelect(1, 2) == 1 {stopProcessOnPort(port)}fmt.Scanln()} else {fmt.Printf("端口号:%d没有被占用\n", port)}fmt.Printf("\n\n")}
}// 检测端口是否被占用
func isPortInUse(port int) bool {listener, err := net.Listen("tcp", ":"+strconv.Itoa(port))if err != nil {return true}defer listener.Close()return false
}// 停止占用指定端口的进程
func stopProcessOnPort(port int) {cmd := exec.Command("netstat", "-ano")output, err := cmd.Output()if err != nil {log.Fatal(err)}lines := strings.Split(string(output), "\n")for _, line := range lines {fields := strings.Fields(line)if len(fields) >= 4 && strings.HasSuffix(fields[1], ":"+strconv.Itoa(port)) {pid, err := strconv.Atoi(fields[4])if err != nil {log.Println("无法获取该端口号的id:", err)return}killCmd := exec.Command("taskkill", "/F", "/PID", strconv.Itoa(pid))if err := killCmd.Run(); err != nil {log.Println("终止该进程失败:", err)return}fmt.Printf("进程号 %d 端口号 %d 已经被停止\n", pid, port)return}}
}
运行
运行链接
b站运行视频