Java教程

InetAddress对象的使用

本文主要是介绍InetAddress对象的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package demo03;

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

public class API {
    public static void main(String[] args) throws UnknownHostException {
//        获取本机inetAddress对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);

//        根据主机名获取inetAddress对象
        InetAddress host1 = InetAddress.getByName("ZX");
        System.out.println(host1);

//        根据域名返回inetAddress对象
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        System.out.println(host2);

//        通过InetAddress对象,获取对应的地址
        String hostAddress = host2.getHostAddress();
        System.out.println("host2对应的IP:"+hostAddress);

//        通过InetAddress对象,获取域名或者主机名
        String name1 = host2.getHostName();
        String name2 = host1.getHostName();
        System.out.println(name1+"\n"+name2);
    }
}

这篇关于InetAddress对象的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!