@@ -130,6 +130,25 @@ func ParseFlags(nicBridgeMappings map[string]string) (*Configuration, error) {
130
130
return config , nil
131
131
}
132
132
133
+ func getSrcIPsByRoutes (iface * net.Interface ) ([]string , error ) {
134
+ link , err := netlink .LinkByName (iface .Name )
135
+ if err != nil {
136
+ return nil , fmt .Errorf ("failed to get link %s: %v" , iface .Name , err )
137
+ }
138
+ routes , err := netlink .RouteList (link , netlink .FAMILY_ALL )
139
+ if err != nil {
140
+ return nil , fmt .Errorf ("failed to get routes on link %s: %v" , iface .Name , err )
141
+ }
142
+
143
+ srcIPs := make ([]string , 0 , 2 )
144
+ for _ , r := range routes {
145
+ if r .Src != nil && r .Scope == netlink .SCOPE_LINK {
146
+ srcIPs = append (srcIPs , r .Src .String ())
147
+ }
148
+ }
149
+ return srcIPs , nil
150
+ }
151
+
133
152
func (config * Configuration ) initNicConfig (nicBridgeMappings map [string ]string ) error {
134
153
var (
135
154
iface * net.Interface
@@ -171,16 +190,29 @@ func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string)
171
190
klog .Errorf ("failed to find iface %s, %v" , tunnelNic , err )
172
191
return err
173
192
}
193
+ srcIPs , err := getSrcIPsByRoutes (iface )
194
+ if err != nil {
195
+ return fmt .Errorf ("failed to get src IPs by routes on interface %s: %v" , iface .Name , err )
196
+ }
174
197
addrs , err := iface .Addrs ()
175
198
if err != nil {
176
199
return fmt .Errorf ("failed to get iface addr. %v" , err )
177
200
}
178
- if len (addrs ) == 0 {
179
- return fmt .Errorf ("iface %s has no ip address" , tunnelNic )
201
+ for _ , addr := range addrs {
202
+ ipStr := strings .Split (addr .String (), "/" )[0 ]
203
+ if ip := net .ParseIP (ipStr ); ip == nil || ip .IsLinkLocalUnicast () {
204
+ continue
205
+ }
206
+ if len (srcIPs ) == 0 || util .ContainsString (srcIPs , ipStr ) {
207
+ encapIP = ipStr
208
+ break
209
+ }
210
+ }
211
+ if len (encapIP ) == 0 {
212
+ return fmt .Errorf ("iface %s has no valid IP address" , tunnelNic )
180
213
}
181
- encapIP = strings .Split (addrs [0 ].String (), "/" )[0 ]
182
214
183
- klog .Infof ("use %s as tunnel interface" , iface .Name )
215
+ klog .Infof ("use %s on %s as tunnel address" , encapIP , iface .Name )
184
216
config .tunnelIface = iface .Name
185
217
}
186
218
0 commit comments