取得应用服务器端的IP地址(Windows Unix Linux)

本文提供了一种使用Java代码在Linux环境下获取本机IP地址的方法。通过遍历网络接口并筛选出非回环地址,实现了有效地获取实际可用的IP地址。

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

取得应用服务器端的IP地址
参考
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
http://faq.youkuaiyun.com/read/3301.html

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class LinuxInetAddress {
/**
* 遍历本机网卡中所有的IP地址,Linux操作系统对应
*/
public static String getLocalIpAddress() {
String result = "";
try {
// 根据网卡取本机配置的 IP
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = InetAddress.getLocalHost();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
ip = (InetAddress) ni.getInetAddresses().nextElement();
// Reference
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
// !ip.isSiteLocalAddress() && is deleted by zcwang
if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
result = ip.getHostAddress();
break;
} else {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值