Skip to content

Commit bf4076b

Browse files
author
Kelven Yang
committed
Fix the problem in retrieving default host IP on windows platform
1 parent f157148 commit bf4076b

1 file changed

Lines changed: 46 additions & 14 deletions

File tree

‎utils/src/com/cloud/utils/net/NetUtils.java‎

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
*/
1818
package com.cloud.utils.net;
1919

20+
import java.io.BufferedReader;
2021
import java.io.File;
22+
import java.io.InputStreamReader;
2123
import java.lang.reflect.Array;
2224
import java.net.InetAddress;
2325
import java.net.InterfaceAddress;
@@ -33,6 +35,8 @@
3335
import java.util.Set;
3436
import java.util.StringTokenizer;
3537
import java.util.TreeSet;
38+
import java.util.regex.Matcher;
39+
import java.util.regex.Pattern;
3640

3741
import org.apache.log4j.Logger;
3842
import org.apache.log4j.xml.DOMConfigurator;
@@ -140,22 +144,50 @@ public static String[] getLocalCidrs() {
140144
return cidrList.toArray(new String[0]);
141145
}
142146

147+
private static boolean isWindows() {
148+
String os = System.getProperty("os.name");
149+
if(os != null && os.startsWith("Windows"))
150+
return true;
151+
152+
return false;
153+
}
154+
143155
public static String getDefaultHostIp() {
144-
NetworkInterface nic = null;
145-
String pubNic = getDefaultEthDevice();
146-
147-
if (pubNic == null) {
148-
return null;
156+
if(isWindows()) {
157+
Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*");
158+
try {
159+
Process result = Runtime.getRuntime().exec("route print -4");
160+
BufferedReader output = new BufferedReader
161+
(new InputStreamReader(result.getInputStream()));
162+
163+
String line = output.readLine();
164+
while(line != null){
165+
Matcher matcher = pattern.matcher(line);
166+
if (matcher.find()) {
167+
return matcher.group(2);
168+
}
169+
line = output.readLine();
170+
}
171+
} catch( Exception e ) {
172+
}
173+
return null;
174+
} else {
175+
NetworkInterface nic = null;
176+
String pubNic = getDefaultEthDevice();
177+
178+
if (pubNic == null) {
179+
return null;
180+
}
181+
182+
try {
183+
nic = NetworkInterface.getByName(pubNic);
184+
} catch (final SocketException e) {
185+
return null;
186+
}
187+
188+
String[] info = NetUtils.getNetworkParams(nic);
189+
return info[0];
149190
}
150-
151-
try {
152-
nic = NetworkInterface.getByName(pubNic);
153-
} catch (final SocketException e) {
154-
return null;
155-
}
156-
157-
String[] info = NetUtils.getNetworkParams(nic);
158-
return info[0];
159191
}
160192

161193
public static String getDefaultEthDevice() {

0 commit comments

Comments
 (0)