JAVA网络编程的包在java.net包中
获取本机的ip地址可以通过net中的InetAddress类进行
例子:
需要抛出异常 UnknownHostException 因为可能获取不到主机
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Demo {
public static void main(String[] args) throws UnknownHostException {
//没有构造方法...通过类名.方法获取
InetAddress ip =InetAddress.getLocalHost();
//ip地址
System.out.println(ip.getHostAddress());
//主机名
System.out.println(ip.getHostName());
}
}
运行结果:
可以通过域名获取其它主机的ip地址
例子:
这里用www.baidu.com
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Demo {
public static void main(String[] args) throws UnknownHostException {
InetAddress ip = InetAddress.getLocalHost();
ip = ip.getByName("www.baidu.com");
System.out.println(ip.getHostAddress());
}
}
运行结果: 183.232.231.174