代码
package main
import (
"fmt"
"log"
"net"
"os/exec"
"strconv"
"strings"
)
func getSelect(beign int, end int) int {
var num int
for {
_, 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 int
for {
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
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
运行链接
b站运行视频