这段程序不能返回IP地址?看看吧!

rwq_ 2001-07-21 11:56:50
import java.net.*;
public class InetAddressTest
{ public static void main(String[] args)
{ try
{
if (args.length > 0)
{ String host = args[0];
InetAddress[] addresses
= InetAddress.getAllByName(host);
for (int i = 0; i < addresses.length; i++)
System.out.println(addresses[i]);
}
else
{ InetAddress localHostAddress= InetAddress.getLocalHost();
System.out.println(localHostAddress);
byte[] ID=new byte[20];
ID=localHostAddress.getAddress();
String SID=localHostAddress.getHostName();
System.out.println(ID);//这里为什么不能返回IP地址? System.out.println(SID);
}
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
}

运行结果:
ruanwq/10.16.251.133
[B@53c015
ruanwq

那路朋友看看?
...全文
60 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gxj0637 2001-07-21
  • 打赏
  • 举报
回复
因为ID是byte[],不能正常显示,用getHostAddress()就可以。
masterz 2001-07-21
  • 打赏
  • 举报
回复
import java.net.*;
public class InetAddressTest
{ public static void main(String[] args)
{ try
{
if (args.length > 0)
{ String host = args[0];
InetAddress[] addresses
= InetAddress.getAllByName(host);
for (int i = 0; i < addresses.length; i++)
System.out.println(addresses[i]);
}
else
{ InetAddress localHostAddress= InetAddress.getLocalHost();
System.out.println(localHostAddress);
byte[] ID=new byte[20];
ID=localHostAddress.getAddress();
String SID=localHostAddress.getHostName();
System.out.println(ID);//这里为什么不能返回IP地址? System.out.println(SID);
System.out.print( "IP is :");
for(int i=0;i<4;i++)
{
int a = ID[i]&0xFF;
System.out.print(a);
if(i<3)
System.out.print(".");
}
System.out.println();
}
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
}
knight_qmh 2001-07-21
  • 打赏
  • 举报
回复
String getHostAddress()
Returns the IP address string "%d.%d.%d.%d".

String SID=localHostAddress.getHostAddress();

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧