Skip to content

Commit f2f9cb5

Browse files
authored
[INLONG-11869][SDK]Obtain a valid ip during initialization (#11870)
1 parent cf0b832 commit f2f9cb5

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

inlong-sdk/dataproxy-sdk-twins/dataproxy-sdk-golang/dataproxy/options.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,9 @@ var (
4141

4242
func init() {
4343
var err error
44-
localIP, err = util.GetFirstPrivateIP()
44+
localIP, err = util.GetOneIP()
4545
if err != nil {
46-
localIP, err = util.GetFirstIP()
47-
if err != nil {
48-
localIP = "noIP"
49-
}
46+
localIP = "noIP"
5047
}
5148
}
5249

inlong-sdk/dataproxy-sdk-twins/dataproxy-sdk-golang/util/id.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ var (
2929
)
3030

3131
func init() {
32-
ip, err := GetFirstPrivateIP()
32+
ip, err := GetOneIP()
3333
if err != nil {
3434
log.Fatal(err)
3535
}

inlong-sdk/dataproxy-sdk-twins/dataproxy-sdk-golang/util/ip.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,23 @@ func GetFirstIP() (string, error) {
154154

155155
return "", fmt.Errorf("no ip")
156156
}
157+
158+
// GetOneIP obtain a valid ip address of the current host, with private ip preferred
159+
func GetOneIP() (string, error) {
160+
ips, err := GetIPv4List()
161+
if err != nil {
162+
return "", fmt.Errorf("failed to obtain ip. %w", err)
163+
}
164+
165+
if len(ips) == 0 {
166+
return "", fmt.Errorf("no ip")
167+
}
168+
169+
for _, ip := range ips {
170+
if IsPrivateIP(ip) {
171+
return ip, nil
172+
}
173+
}
174+
175+
return ips[0], nil
176+
}

0 commit comments

Comments
 (0)