/**
* 获取公网ip
* @return
*/
public String getNetIp() {
URL infoUrl = null;
InputStream inStream = null;
try {
infoUrl = new URL("http://iframe.ip138.com/ic.asp");
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"gb2312"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
System.out.println("net-result----->"+strber);
//从反馈的结果中提取出IP地址
int start = strber.indexOf("[");
int end = strber.indexOf("]", start + 1);
line = strber.substring(start + 1, end);
return line;
}
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取内网ip
* @return
*/
private String getLocalIPAddress(){
try {
for(Enumeration en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for(Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "null";
}