Skip to content

Commit

Permalink
当 9080 端口被占用时,随机一个 60000 以上的端口号作为监听
Browse files Browse the repository at this point in the history
  • Loading branch information
yhy0 committed May 18, 2023
1 parent 2be900c commit 85d5f9a
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ func (a *App) startup(ctx context.Context) {
burpSuite.Init()
burpSuite.HotConf()

if utils.IsPortOccupied(burpSuite.Settings.ProxyPort) {
port, err := utils.GetRandomUnusedPort()
if err != nil {
logging.Logger.Errorln(err)
burpSuite.Settings.ProxyPort = 65530
}
burpSuite.Settings.ProxyPort = port
}

go burpSuite.Run(burpSuite.Settings.ProxyPort)

runtime.EventsEmit(ctx, "ProxyPort", burpSuite.Settings.ProxyPort)
Expand Down
32 changes: 32 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package utils

import (
"fmt"
"math/rand"
"net"
"os"
"time"
)

/**
Expand All @@ -12,6 +14,7 @@ import (
@desc: //TODO
**/

// IsPortOccupied 判断端口号是否被占用
func IsPortOccupied(port int) bool {
address := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", address)
Expand All @@ -22,6 +25,35 @@ func IsPortOccupied(port int) bool {
return false // 端口未被占用
}

// GetRandomUnusedPort 随机获取一个在 60000 以上的端口号
func GetRandomUnusedPort() (int, error) {
// 设置随机数种子
rand.Seed(time.Now().UnixNano())

// 定义起始端口号和端口号范围,并生成一个随机整数
basePort := 60000
portRange := 65535 - basePort + 1
randomOffset := rand.Intn(portRange)

// 计算出最终的端口号
port := basePort + randomOffset

// 创建一个 TCP 地址对象
addr := &net.TCPAddr{IP: nil, Port: port}

// 使用 ListenTCP 函数创建一个新的 TCP 监听器,并返回一个 TCP 地址对象
listener, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}

// 关闭监听器
defer listener.Close()

// 获取监听器的地址对象,并返回其端口号作为结果
return listener.Addr().(*net.TCPAddr).Port, nil
}

// Exists 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
Expand Down
5 changes: 5 additions & 0 deletions test/test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"github.com/yhy0/ChYing/pkg/file"
"github.com/yhy0/ChYing/pkg/utils"
"github.com/yhy0/ChYing/tools"
"github.com/yhy0/ChYing/tools/burpSuite"
"github.com/yhy0/logging"
Expand Down Expand Up @@ -132,4 +133,8 @@ svchost.exe 5056 Services 0 3,316 K
svchost.exe
`
fmt.Println(tools.Tasklist(out))

port, err := utils.GetRandomUnusedPort()

fmt.Println(port)
}

0 comments on commit 85d5f9a

Please sign in to comment.