日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java获取本机的外网IP地址(亲测有效)

發布時間:2023/12/18 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java获取本机的外网IP地址(亲测有效) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

獲取本機的外網地址?

如果下面正確,請留下您寶貴的贊

package untils;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.*; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern;/*** @author CBeann* @create 2020-04-13 1:31*/ public class IPUntils {public static void main(String[] args) throws Exception {System.out.println(IPUntils.getInterIP1());System.out.println(IPUntils.getInterIP2());System.out.println(IPUntils.getOutIPV4());}public static String getInterIP1() throws Exception {return InetAddress.getLocalHost().getHostAddress();}public static String getInterIP2() throws SocketException {String localip = null;// 本地IP,如果沒有配置外網IP則返回它String netip = null;// 外網IPEnumeration<NetworkInterface> netInterfaces;netInterfaces = NetworkInterface.getNetworkInterfaces();InetAddress ip = null;boolean finded = false;// 是否找到外網IPwhile (netInterfaces.hasMoreElements() && !finded) {NetworkInterface ni = netInterfaces.nextElement();Enumeration<InetAddress> address = ni.getInetAddresses();while (address.hasMoreElements()) {ip = address.nextElement();if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外網IPnetip = ip.getHostAddress();finded = true;break;} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 內網IPlocalip = ip.getHostAddress();}}}if (netip != null && !"".equals(netip)) {return netip;} else {return localip;}}public static String getOutIPV4() {String ip = "";String chinaz = "http://ip.chinaz.com";StringBuilder inputLine = new StringBuilder();String read = "";URL url = null;HttpURLConnection urlConnection = null;BufferedReader in = null;try {url = new URL(chinaz);urlConnection = (HttpURLConnection) url.openConnection();in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));while ((read = in.readLine()) != null) {inputLine.append(read + "\r\n");}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");Matcher m = p.matcher(inputLine.toString());if (m.find()) {String ipstr = m.group(1);ip = ipstr;}return ip;} }

總結

以上是生活随笔為你收集整理的java获取本机的外网IP地址(亲测有效)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。