|
17 | 17 | */ |
18 | 18 | package com.cloud.utils.net; |
19 | 19 |
|
| 20 | +import java.io.BufferedReader; |
20 | 21 | import java.io.File; |
| 22 | +import java.io.InputStreamReader; |
21 | 23 | import java.lang.reflect.Array; |
22 | 24 | import java.net.InetAddress; |
23 | 25 | import java.net.InterfaceAddress; |
|
33 | 35 | import java.util.Set; |
34 | 36 | import java.util.StringTokenizer; |
35 | 37 | import java.util.TreeSet; |
| 38 | +import java.util.regex.Matcher; |
| 39 | +import java.util.regex.Pattern; |
36 | 40 |
|
37 | 41 | import org.apache.log4j.Logger; |
38 | 42 | import org.apache.log4j.xml.DOMConfigurator; |
@@ -140,22 +144,50 @@ public static String[] getLocalCidrs() { |
140 | 144 | return cidrList.toArray(new String[0]); |
141 | 145 | } |
142 | 146 |
|
| 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 | + |
143 | 155 | 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]; |
149 | 190 | } |
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]; |
159 | 191 | } |
160 | 192 |
|
161 | 193 | public static String getDefaultEthDevice() { |
|
0 commit comments