From 084351a063322e020385a13428a167a436edbd92 Mon Sep 17 00:00:00 2001 From: ssongliu <73214554+ssongliu@users.noreply.github.com> Date: Wed, 25 Oct 2023 11:13:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=91=BD=E4=BB=A4=E8=A1=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=88=87=E6=8D=A2=E7=9B=91=E5=90=AC=20IP=20(#2671)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/server/cmd/listen-ip.go | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 cmd/server/cmd/listen-ip.go diff --git a/cmd/server/cmd/listen-ip.go b/cmd/server/cmd/listen-ip.go new file mode 100644 index 000000000..c0168878f --- /dev/null +++ b/cmd/server/cmd/listen-ip.go @@ -0,0 +1,60 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +func init() { + RootCmd.AddCommand(listenCmd) + listenCmd.AddCommand(listenIpv4Cmd) + listenCmd.AddCommand(listenIpv6Cmd) +} + +var listenCmd = &cobra.Command{ + Use: "listen-ip", + Short: "切换监听 IP", +} + +var listenIpv4Cmd = &cobra.Command{ + Use: "ipv4", + Short: "监听 IPv4", + RunE: func(cmd *cobra.Command, args []string) error { + return updateBindInfo("ipv4") + }, +} +var listenIpv6Cmd = &cobra.Command{ + Use: "ipv6", + Short: "监听 IPv6", + RunE: func(cmd *cobra.Command, args []string) error { + return updateBindInfo("ipv6") + }, +} + +func updateBindInfo(protocol string) error { + if !isRoot() { + fmt.Println("请使用 sudo 1pctl listen-ip ipv6 或者切换到 root 用户") + return nil + } + db, err := loadDBConn() + if err != nil { + return err + } + ipv6 := "disable" + tcp := "tcp4" + address := "0.0.0.0" + if protocol == "ipv6" { + ipv6 = "enable" + tcp = "tcp6" + address = "::" + } + if err := setSettingByKey(db, "Ipv6", ipv6); err != nil { + return err + } + if err := setSettingByKey(db, "BindAddress", address); err != nil { + return err + } + fmt.Printf("切换成功!已切换至监听 %s [%s]", tcp, address) + return nil +}