首页 > 代码库 > Java网络通信

Java网络通信

netAddress类

java.net包中的InetAddress类是与IP地址相关的类,利用该类可以获取IP地址、主机地址等信息。


import java.net.InetAddress;
import java.net.UnknownHostException;

public class Address {
    public static void main(String[] args) {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();
            String localname = ip.getHostName();
            String localip = ip.getHostAddress();
            System.out.println("本机名/本机IP地址:" + ip);
            System.out.println("本机名:" + localname);
            System.out.println("本机IP地址:" + localip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}


Java网络通信