获取本地IP地址和主机名

时间:2022-05-31 03:37:01
                                        获取本地IP地址和主机名[转贴]
/* FileName:IPHomework.java Author:流浪小子 Date:2004-7-5 E-mail:qiyadeng@hotmail.com
 Purpose:获取本地主机的IP地址和主机名 */
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPHomework {
InetAddress addr=null;
 byte[] ipAddr=null;
String hostname="";
String ipAddress="";
public static void main(String arg[]) { IPHomework ip=new IPHomework();
System.out.println("The LocalHost's IP is: "+ip.getLocalHostIP ());
System.out.println("The LocalHost's HostName is: "+ip.getLocalHostName());
}
 public String getLocalHostIP()
 {
try { addr=InetAddress.getLocalHost ();
 ipAddr=addr.getAddress ();
for(int i=0;i 0)
{ ipAddress+="."; }
ipAddress+=ipAddr[i]&0xFF;
}
} catch(UnknownHostException e) { }
return ipAddress;
}
public String getLocalHostName() {
 try {
addr=InetAddress.getLocalHost ();
 hostname=addr.getHostName ();
} catch(UnknownHostException e) { }
 return hostname;
}
}
;++i)>