// 获取本机的ip
public String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String ipLine = "";
HttpURLConnection httpConnection = null;
try {
// http://city.ip138.com/ip2city.asp    本地子ip
// http://www.cmyip.com/
infoUrl = new URL("http://www.cmyip.com/");
URLConnection connection = infoUrl.openConnection();
httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");


Pattern pattern = Pattern
.compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
Matcher matcher = pattern.matcher(strber.toString());
if (matcher.find()) {
ipLine = matcher.group();
}
}


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inStream != null) {
inStream.close();
}
httpConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return ipLine;

}


温馨提示:本方法执行不能再主线程中执行,否则会出现NetworkOnMainThreadException异常

更多相关文章

  1. Android 获取网络图片方法
  2. android 游戏 Canvas 常用方法
  3. Android中为Button注册监听器最常用的两种方法
  4. Android 保留两位小数点的4种方法
  5. Android MultiDex 解决 64K 限制,方法数超过65535解决方法
  6. [android]简单方法记载 在adapter中异步加载网络图片

随机推荐

  1. Android(安卓)特殊符号的ASCII转码
  2. Android(安卓)Studio3.0及Gradle4.1带来
  3. Android(安卓)开源动画框架 NineOldAndro
  4. Android(安卓)开发 ------------- Unable
  5. Android异步任务处理之AsyncTaskLoader的
  6. Android(安卓)Studio版本升级与降级
  7. android listView.getCount 与 listView.
  8. 修改Android模拟器RAM大小方法
  9. Android导入多个Module时包冲突解决办法
  10. Android(安卓)jni GetFieldID 和 GetMeth