Skip to content

Commit

Permalink
feat: support plain text response that only return the ip address (#106)
Browse files Browse the repository at this point in the history
* feat: support plain text response that only return the ip address

* feat: check if the IP address is valid
  • Loading branch information
xream authored Dec 1, 2024
1 parent ea6f119 commit 7db8d90
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions pkg/monitor/myip.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package monitor

import (
"io"
"net"
"net/http"
"strings"
"sync"
Expand Down Expand Up @@ -93,20 +94,28 @@ func fetchIP(servers []string, isV6 bool) string {
continue
}
resp.Body.Close()
lines := strings.Split(string(body), "\n")

bodyStr := string(body)
var newIP string
for _, line := range lines {
if strings.HasPrefix(line, "ip=") {
newIP = strings.TrimPrefix(line, "ip=")
break

if !strings.Contains(bodyStr, "ip=") {
newIP = strings.TrimSpace(strings.ReplaceAll(bodyStr, "\n", ""))
} else {
lines := strings.Split(bodyStr, "\n")
for _, line := range lines {
if strings.HasPrefix(line, "ip=") {
newIP = strings.TrimPrefix(line, "ip=")
break
}
}
}
parsedIP := net.ParseIP(newIP)
// 没取到 v6 IP
if isV6 && strings.IndexByte(newIP, ':') == -1 {
if isV6 && (parsedIP == nil || parsedIP.To4() != nil) {
continue
}
// 没取到 v4 IP
if !isV6 && strings.IndexByte(newIP, '.') == -1 {
if !isV6 && (parsedIP == nil || parsedIP.To4() == nil) {
continue
}
ip = newIP
Expand Down

0 comments on commit 7db8d90

Please sign in to comment.