Skip to content

Commit

Permalink
fix: fix the logic of obtaining ip
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Apr 22, 2023
1 parent 0862725 commit 40ae1c8
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
2 changes: 1 addition & 1 deletion common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const (

var (
Port = flag.Int("port", 3000, "Specify the server listening port.")
Host = flag.String("host", "localhost", "The server's IP address or domain.")
Host = flag.String("host", "", "The server's IP address or domain.")
Path = flag.String("path", "", "Specify a local path to public.")
VideoPath = flag.String("video", "", "Specify a folder containing videos to be made public.")
NoBrowser = flag.Bool("no-browser", false, "Do not open browser automatically.")
Expand Down
27 changes: 20 additions & 7 deletions common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,30 +23,43 @@ func OpenBrowser(url string) {
}

func GetIp() (ip string) {
backupIp := "127.0.0.1"
ips, err := net.InterfaceAddrs()
if err != nil {
SysError("failed to get IP address: " + err.Error())
return ip
return backupIp
}

for _, a := range ips {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ip = ipNet.IP.String()
if strings.HasPrefix(ip, "10") {
return
// Class A: 10.0.0.0 to 10.255.255.255
backupIp = ip
continue
}
if strings.HasPrefix(ip, "172") {
return
// Class B: 172.16.0.0 to 172.31.255.255
parts := strings.Split(ip, ".")
secondPart, err := strconv.Atoi(parts[1])
if err != nil {
continue
}
if secondPart >= 16 && secondPart <= 31 {
backupIp = ip
continue
}
}
if strings.HasPrefix(ip, "192.168") {
return
// Class C: 192.168.0.0 to 192.168.255.255
backupIp = ip
continue
}
ip = ""
return
}
}
}
return
return backupIp
}

var sizeKB = 1024
Expand Down
4 changes: 3 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,12 @@ func main() {
if realPort == "" {
realPort = strconv.Itoa(*common.Port)
}
if *common.Host == "localhost" {
if *common.Host == "" {
ip := common.GetIp()
if ip != "" {
*common.Host = ip
} else {
*common.Host = "localhost"
}
}
serverUrl := "http://" + *common.Host + ":" + realPort + "/"
Expand Down

0 comments on commit 40ae1c8

Please sign in to comment.