Skip to content

Commit cf0b832

Browse files
authored
[INLONG-11865][SDK] Optimize the acquisition of local valid IP addresses (#11866)
1 parent 8a54dc4 commit cf0b832

File tree

1 file changed

+43
-14
lines changed
  • inlong-sdk/dataproxy-sdk-twins/dataproxy-sdk-golang/util

1 file changed

+43
-14
lines changed

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

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -74,21 +74,54 @@ func IsPrivateIP(ip string) bool {
7474
return false
7575
}
7676

77+
// GetIPv4List obtain all valid local addresses
78+
func GetIPv4List() ([]string, error) {
79+
interfaces, err := net.Interfaces()
80+
if err != nil {
81+
return nil, err
82+
}
83+
84+
var ipv4List []string
85+
for _, iface := range interfaces {
86+
if iface.Flags&net.FlagUp == 0 {
87+
continue
88+
}
89+
90+
addrs, err := iface.Addrs()
91+
if err != nil {
92+
continue
93+
}
94+
95+
for _, addr := range addrs {
96+
ipNet, ok := addr.(*net.IPNet)
97+
if !ok {
98+
continue
99+
}
100+
101+
ip := ipNet.IP
102+
if ip.IsLoopback() || ip.IsLinkLocalUnicast() {
103+
continue
104+
}
105+
106+
if ipv4 := ip.To4(); ipv4 != nil {
107+
ipv4List = append(ipv4List, ipv4.String())
108+
}
109+
}
110+
}
111+
return ipv4List, nil
112+
}
113+
77114
// GetPrivateIPList gets all the private IPs of the current host
78115
func GetPrivateIPList() ([]string, error) {
79-
ips, err := net.InterfaceAddrs()
116+
ips, err := GetIPv4List()
80117
if err != nil {
81118
return nil, err
82119
}
83120

84121
var privateIPs []string
85122
for _, ip := range ips {
86-
parts := strings.Split(ip.String(), "/")
87-
if len(parts) != 2 {
88-
return nil, fmt.Errorf("ip %v address format error", ip.String())
89-
}
90-
if IsPrivateIP(parts[0]) {
91-
privateIPs = append(privateIPs, parts[0])
123+
if IsPrivateIP(ip) {
124+
privateIPs = append(privateIPs, ip)
92125
}
93126
}
94127

@@ -110,17 +143,13 @@ func GetFirstPrivateIP() (string, error) {
110143

111144
// GetFirstIP gets the first IP of the current host
112145
func GetFirstIP() (string, error) {
113-
ips, err := net.InterfaceAddrs()
146+
ips, err := GetIPv4List()
114147
if err != nil {
115148
return "", err
116149
}
117150

118-
for _, ip := range ips {
119-
parts := strings.Split(ip.String(), "/")
120-
if len(parts) != 2 {
121-
continue
122-
}
123-
return parts[0], nil
151+
if len(ips) > 0 {
152+
return ips[0], nil
124153
}
125154

126155
return "", fmt.Errorf("no ip")

0 commit comments

Comments
 (0)