Skip to content

Commit 40ae1c8

Browse files
committed
fix: fix the logic of obtaining ip
1 parent 0862725 commit 40ae1c8

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

common/constants.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ const (
5555

5656
var (
5757
Port = flag.Int("port", 3000, "Specify the server listening port.")
58-
Host = flag.String("host", "localhost", "The server's IP address or domain.")
58+
Host = flag.String("host", "", "The server's IP address or domain.")
5959
Path = flag.String("path", "", "Specify a local path to public.")
6060
VideoPath = flag.String("video", "", "Specify a folder containing videos to be made public.")
6161
NoBrowser = flag.Bool("no-browser", false, "Do not open browser automatically.")

common/utils.go

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,30 +23,43 @@ func OpenBrowser(url string) {
2323
}
2424

2525
func GetIp() (ip string) {
26+
backupIp := "127.0.0.1"
2627
ips, err := net.InterfaceAddrs()
2728
if err != nil {
2829
SysError("failed to get IP address: " + err.Error())
29-
return ip
30+
return backupIp
3031
}
31-
3232
for _, a := range ips {
3333
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
3434
if ipNet.IP.To4() != nil {
3535
ip = ipNet.IP.String()
3636
if strings.HasPrefix(ip, "10") {
37-
return
37+
// Class A: 10.0.0.0 to 10.255.255.255
38+
backupIp = ip
39+
continue
3840
}
3941
if strings.HasPrefix(ip, "172") {
40-
return
42+
// Class B: 172.16.0.0 to 172.31.255.255
43+
parts := strings.Split(ip, ".")
44+
secondPart, err := strconv.Atoi(parts[1])
45+
if err != nil {
46+
continue
47+
}
48+
if secondPart >= 16 && secondPart <= 31 {
49+
backupIp = ip
50+
continue
51+
}
4152
}
4253
if strings.HasPrefix(ip, "192.168") {
43-
return
54+
// Class C: 192.168.0.0 to 192.168.255.255
55+
backupIp = ip
56+
continue
4457
}
45-
ip = ""
58+
return
4659
}
4760
}
4861
}
49-
return
62+
return backupIp
5063
}
5164

5265
var sizeKB = 1024

main.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,12 @@ func main() {
7272
if realPort == "" {
7373
realPort = strconv.Itoa(*common.Port)
7474
}
75-
if *common.Host == "localhost" {
75+
if *common.Host == "" {
7676
ip := common.GetIp()
7777
if ip != "" {
7878
*common.Host = ip
79+
} else {
80+
*common.Host = "localhost"
7981
}
8082
}
8183
serverUrl := "http://" + *common.Host + ":" + realPort + "/"

0 commit comments

Comments
 (0)