我用如下方法:
public static String getLocalIP() {
String ipAdress = "";
String myHost = "";
InetAddress myIPaddress = null;
try {
myIPaddress = InetAddress.getLocalHost();
myHost = myIPaddress.toString();
ipAdress = myHost.substring(myHost.indexOf("/") + 1, myHost
.length());// ip部分
} catch (UnknownHostException e) {
}
return (ipAdress);
}
在windows下可以得到真实ip,但是在linux下运行时,得到的却是127.0.0.1
如何才能在linux下得到真正的本机ip呢?请教各位!谢谢:)
public static String getLocalIP() {
String ipAdress = "";
String myHost = "";
InetAddress myIPaddress = null;
try {
myIPaddress = InetAddress.getLocalHost();
myHost = myIPaddress.toString();
ipAdress = myHost.substring(myHost.indexOf("/") + 1, myHost
.length());// ip部分
} catch (UnknownHostException e) {
}
return (ipAdress);
}
在windows下可以得到真实ip,但是在linux下运行时,得到的却是127.0.0.1
如何才能在linux下得到真正的本机ip呢?请教各位!谢谢:)
解决方案 »
- 请帮个忙。谢谢。编译时出错
- 做表情
- 我做c/s啊想用连接池啊!!!!!!!!!!!!但是没找到相关资料啊
- 初学者,遇到一个小麻烦,请各位帮帮我。。。。。。
- 【求助】"虚拟内存"、"内存使用"、"高峰内存"代表什么意义
- 大家帮忙看看这个执行期异常怎么改
- 什么叫重量级和轻量级,粗粒度(Coarse-grained)和细粒度(fine-grained)区别又在哪?
- 请问
- 急急急! 用javamail写了一个发信程序,可是报"javax.mail.NoSuchProviderException: No provider for pop3 pr
- Java中static一般有什么作用
- java.util.logging.Logger??
- rs.last()很慢的问题
首先谢谢llhdf(塞外浪子) !解决过程如下:
在出现问题后,查找到网上有关资料,别人是这样解决:
java获取本机的ip地址-解决Linux下取得IP为127.0.0.1问题 可以用如下代码: InetAddress inet = InetAddress.getLocalHost();
System.out.println("本机的ip=" + inet.getHostAddress());
在window下面可以工作。在linux下返回127.0.0.1。主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址,
而不是网卡的绑定地址。后来改用网卡的绑定地址,可以取到本机的ip地址:)代码如下://根据网卡取本机配置的IP
Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while(netInterfaces.hasMoreElements())
{
NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();
System.out.println(ni.getName());
ip=(InetAddress) ni.getInetAddresses().nextElement();
if( !ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":")==-1)
{
System.out.println("本机的ip=" + ip.getHostAddress());
break;
}
else
{
ip=null;
}
}套用别人的代码,我的报错:空指针错误!抓头!!
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1 localhost.localdomain localhost
XXX.XX.X.XXX test.com所以就对我的代码进行如下调整:
public static String test() throws UnknownHostException{
InetAddress all;
StringBuffer sb = new StringBuffer();
all = InetAddress.getByName("test.com");
// all = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
String s = all.getHostAddress();
return s;
}ok了!