1 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
test.go 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2024-12-08 22:35 . update wg client
package main
import (
"fmt"
"log"
"testing"
"time"
"gitee.com/carlmax_my/console-core-go/vpn/linker"
"github.com/samber/lo"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
func main() {
runTest()
}
// var okDevice = &wgtypes.Device{Name: "wg0"}
func TestClient(t *testing.T) {
runTest()
}
func runTest() {
// 设置你要修改的WireGuard接口的名称
ifName := "wg0"
iface, err := linker.CreateTun(ifName)
if err != nil {
log.Println("linker.CreateTun err", err.Error())
log.Fatal(err)
}
log.Println("CreateTun success", ifName, iface)
var client *wgctrl.Client
for {
time.Sleep(5 * time.Second)
client, err = checkDevice(iface)
if err != nil {
log.Printf("checkDevice error: %s\n", err.Error())
} else {
break
}
}
TestCfg(client, iface)
}
func checkDevice(iface string) (*wgctrl.Client, error) {
// 打开wgctrl客户端
client, err := wgctrl.New()
if err != nil {
return nil, fmt.Errorf("wgctrl.New err: %s", err.Error())
}
defer client.Close()
devices, err := client.Devices()
if err != nil {
return nil, fmt.Errorf("client.Devices err: %s", err.Error())
}
log.Printf("devices=%+v;%d\n", devices, len(devices))
device, err := client.Device(iface)
if err != nil {
return nil, fmt.Errorf("client.Device err: %s", err.Error())
}
log.Printf("client.Device success: %+v", *device)
return client, nil
}
func TestCfg(client *wgctrl.Client, iface string) error {
cfg := wgtypes.Config{
ListenPort: lo.ToPtr(51821),
}
// 应用新的配置
if err := client.ConfigureDevice(iface, cfg); err != nil {
return fmt.Errorf("client.ConfigureDevice err: %s", err.Error())
}
fmt.Printf("interface %s has been set %+v\n", iface, cfg)
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.0.36

搜索帮助