Java获取本机外网ip地址的方法

短命女 2022-06-14 03:58 642阅读 0赞

Java获取外网IP地址的方法

获取本地IP地址的方法

  1. public static String getLocalAddress(){
  2. String ip = "";
  3. try {
  4. ip = InetAddress.getLocalHost().getHostAddress();
  5. } catch (UnknownHostException e) {
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. }
  9. return ip;
  10. }

获取外网本机的IP地址的方法

一种可行的获取方法,是通过http请求从网站中取出ip字段。例如:http://ip.chinaz.com/

通过这个网址,加上简单的正则表达式,即可得到。

  1. public static String getV4IP(){
  2. String ip = "";
  3. String chinaz = "http://ip.chinaz.com";
  4. StringBuilder inputLine = new StringBuilder();
  5. String read = "";
  6. URL url = null;
  7. HttpURLConnection urlConnection = null;
  8. BufferedReader in = null;
  9. try {
  10. url = new URL(chinaz);
  11. urlConnection = (HttpURLConnection) url.openConnection();
  12. in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
  13. while((read=in.readLine())!=null){
  14. inputLine.append(read+"\r\n");
  15. }
  16. //System.out.println(inputLine.toString());
  17. } catch (MalformedURLException e) {
  18. e.printStackTrace();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }finally{
  22. if(in!=null){
  23. try {
  24. in.close();
  25. } catch (IOException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
  32. Matcher m = p.matcher(inputLine.toString());
  33. if(m.find()){
  34. String ipstr = m.group(1);
  35. ip = ipstr;
  36. //System.out.println(ipstr);
  37. }
  38. return ip;
  39. } 参考博客: http://blog.csdn.NET/dugucanjian/article/details/47378063

发表评论

表情:
评论列表 (有 0 条评论,642人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java获取IP地址方法

            在生产环境要是使用Spring定时任务的话,会在多台机器上定时启动相同的任务,为了保证只在一台机器上执行定时任务,我们在执行定时任务的时候先判断一下当前机器的I