JAVA 获取当前 内网 和 外网 的IP 地址

本文介绍了一个使用Java编写的程序,该程序能够获取并显示计算机的内部局域网IP地址和外部互联网IP地址。通过调用特定的网页服务和利用Java内置的网络功能,程序实现了对外网IP的读取和内网IP的直接获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;

public class UserIP {

/**

  • @param args
  • @throws Exception
    *@author liuwl
    */
    public static void main(String[] args) throws Exception {
    System.out.println(“本机的外网IP是:”+UserIP.getWebIP(“http://www.ip138.com/ip2city.asp”));
    System.out.println(“本机的内网IP是:”+UserIP.getLocalIP());
    }

/**

  • 获取外网地址
  • @param strUrl
  • @return
    */
    public static String getWebIP(String strUrl) {
    try {
    //连接网页
    URL url = new URL(strUrl);
    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    String s = “”;
    StringBuffer sb = new StringBuffer("");
    String webContent = “”;
    //读取网页信息
    while ((s = br.readLine()) != null) {
    sb.append(s + “\r\n”);
    }
    br.close();
    //网页信息
    webContent = sb.toString();
    int start = webContent.indexOf("[")+1;
    int end = webContent.indexOf("]");
    //获取网页中 当前 的 外网IP
    webContent = webContent.substring(start,end);
    return webContent;

} catch (Exception e) {
e.printStackTrace();
return “error open url:” + strUrl;
}
}

public static String getLocalIP() throws Exception{
String localIP = “”;
InetAddress addr = (InetAddress) InetAddress.getLocalHost();
//获取本机IP
localIP = addr.getHostAddress().toString();
return localIP;
}
}
外部链接:https://blog.youkuaiyun.com/LOVELONG8808/article/details/40654325

### Java代码示例用于检索本地设备的MAC地址、公网IP局域网IP #### 获取本地MAC地址 为了获取本机网络接口的MAC地址,可以使用`NetworkInterface`类来枚举所有可用的网络接口并提取其硬件地址。 ```java import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class MacAddressFetcher { public static String getMacAddress() throws SocketException { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); // 过滤掉回环接口其他非活动接口 if (!iface.isLoopback() && iface.isUp()) { byte[] macBytes = iface.getHardwareAddress(); if (macBytes != null) { StringBuilder sb = new StringBuilder(); for (byte b : macBytes) { sb.append(String.format("%02X:", b)); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } } } return "无法找到有效的MAC地址"; } } ``` 此方法遍历所有的网络接口,并返回第一个符合条件(即不是回送接口且处于激活状态)的MAC地址[^1]。 #### 获取局域网IP地址 对于获取局域网内的IPv4地址,同样可以通过`InetAddress`与`NetworkInterface`配合完成: ```java import java.net.*; public class LocalIPAddressFetcher { public static InetAddress getLocalIpAddress() throws UnknownHostException, SocketException { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress instanceof Inet4Address) { return inetAddress; // 返回首个匹配条件的IPv4地址 } } } } catch (SocketException ex) {} throw new UnknownHostException("未能获得局域网IP"); } } ``` 这段代码会查找当前机器上所有非回环(non-loopback) 的 IPv4 地址,并返回其中一个作为代表性的局域网 IP 地址。 #### 获取公网IP地址 要取得外部可见的公共IP,则通常需要借助第三方服务API查询。这里提供一种通过HTTP请求访问特定网站的方式来进行这项工作: ```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class PublicIPAddressFetcher { private static final String PUBLIC_IP_URL = "http://checkip.amazonaws.com/"; public static String fetchPublicIp() throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet(PUBLIC_IP_URL); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(response.getEntity()).trim(); } throw new RuntimeException("Failed to retrieve public IP address."); } } ``` 上述例子利用了Amazon Web Services提供的简单URL来检测客户端的真实外网IP地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值