java 獲得外網ip

來源:互聯網
上載者:User

原理:先訪問 http://1212.ip138.com/ic.asp 得到本機所在的公網ip,然後用JSoup從ip結果頁面中提取出ip。


要在工程中加入JSoup包。


代碼如下:

package main;import java.io.IOException;import java.net.InetAddress;import java.net.UnknownHostException;import org.jsoup.Connection;import org.jsoup.Jsoup;public class Main {/** * 得到原生外網ip,出現異常時返回本地IP * @return */private static String getPublicIP() {String ip = null;try {ip = InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();}org.jsoup.nodes.Document doc = null;Connection con = null;// 串連 http://1212.ip138.com/ic.aspcon = Jsoup.connect("http://1212.ip138.com/ic.asp").timeout(10000); try {doc = con.get();// 獲得包含本機ip的文本串:您的IP是:[xxx.xxx.xxx.xxx] 來自:YYorg.jsoup.select.Elements els = doc.body().select("center");for (org.jsoup.nodes.Element el : els) {ip = el.text(); }// 從文本串過濾出ip,用Regex將非數字和.替換成空串""ip = ip.replaceAll("[^0-9.]", ""); } catch (IOException e) {e.printStackTrace();return ip;}return ip;}public static void main(String[] args) {String str = getPublicIP();System.out.println(str);}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.