InetSocketAddress

由 Toniko 创建, 最后一次修改 2019-07-08

InetSocketAddress测试: 解决端口问题。

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

public class Test {
    public static void main(String[] args) throws UnknownHostException {
        /**
         * 封装端口:在InetAddress基础上+端口。
         */
        //127.0.0.1代表本机,相当于localhost。
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
        /**
         * new InetSocketAddress("127.0.0.1", 9999);内部调用了
         * new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999);
         * 即进行了封装。
         */
//      address = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999);
        System.out.println(address.getHostName());
        System.out.println(address.getPort());
        InetAddress inetAddress = address.getAddress();
        System.out.println(inetAddress.getHostAddress());
        System.out.println(inetAddress.getHostName());

    }
}
以上内容是否对您有帮助:

二维码
建议反馈
二维码