java如何获取公网ip,有通过路由

Python025

java如何获取公网ip,有通过路由,第1张

如果要通过路由器,不同的路由器的获取方法不一样。通用的做法是通过 HttpClient 在百度上搜索关键字 ip, 然后提取出公网ip。

代码如下:

import java.io.BufferedReader

import java.io.IOException

import java.io.InputStream

import java.io.InputStreamReader

import java.net.URL

import java.net.URLConnection

import java.util.regex.Matcher

import java.util.regex.Pattern

public class App {

// 获取网页源码

static String httpGet(String url) {

StringBuffer buffer = new StringBuffer()

try {

URLConnection conn = new URL(url).openConnection()

conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")

try (InputStream inputStream = conn.getInputStream()

InputStreamReader streamReader = new InputStreamReader(inputStream)

BufferedReader reader = new BufferedReader(streamReader)) {

String line = null

while ((line = reader.readLine()) != null) {

buffer.append(line).append(System.lineSeparator())

}

}

} catch (IOException e) {

e.printStackTrace()

}

return buffer.toString()

}

public static void main(String[] args) {

String html = httpGet("https://www.baidu.com/s?wd=ip")

// 提出IP

Pattern pattern = Pattern.compile("<span\\sclass=\"c-gap-right\">本机IP:&nbsp([^<]+)</span>")

Matcher matcher = pattern.matcher(html)

if (matcher.find()) {

String ip = matcher.group(1)

System.out.println(ip)

}

}

}

java获取外网ip地址方法:public class Main {public static void main(String[] args) throws SocketException {System.out.println(Main.getRealIp()) } public static String getRealIp() throws SocketException {String localip = null// 本地IP,如果没有配置外网IP则返回它String netip = null// 外网IP Enumeration<NetworkInterface>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 }}}