InetAddress

2019-07-09 22:33 更新

InetAddress測(cè)試: 解決ip地址問(wèn)題。

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


public class Test {
    public static void main(String[] args) throws UnknownHostException {
        /**
         * InetAddress沒(méi)有封裝端口
         */
        //使用getLocalHost方法創(chuàng)建InetAddress對(duì)象
        InetAddress address = InetAddress.getLocalHost();
        System.out.println(address.getHostAddress());//返回本機(jī)的ip地址
        System.out.println(address.getHostName());//輸出本機(jī)計(jì)算機(jī)名
        //根據(jù)域名得到InetAddress對(duì)象
        address = InetAddress.getByName("www.163.com");
        System.out.println(address.getHostAddress());//輸出163服務(wù)器的ip:125.39.21.3
        System.out.println(address.getHostName());//輸出域名:www.163.com
        //根據(jù)ip得到InetAddress對(duì)象
        address = InetAddress.getByName("125.39.21.3");
        System.out.println(address.getHostAddress());//輸出163服務(wù)器的ip:125.39.21.3
        System.out.println(address.getHostName());//如果ip被解析(DNS)則輸出域名,如果沒(méi)被解析則輸出ip。
    }
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)