繁体   English   中英

在 Java 中创建 InetAddress 对象

[英]Creating InetAddress object in Java

我正在尝试将由 IP 号或名称指定的地址转换为字符串(即localhost127.0.0.1 )为InetAdress对象。 没有构造函数,而是返回InetAddress 的静态方法。 所以如果我得到一个主机名那不是问题,但是如果我得到 IP 号呢? 有一种方法可以获取byte[],但我不确定这对我有什么帮助。 所有其他方法获取主机名。

InetAddress API 文档

您应该能够使用getByNamegetByAddress

主机名可以是机器名称,例如“java.sun.com”,也可以是其 IP 地址的文本表示

InetAddress addr = InetAddress.getByName("127.0.0.1");

可以像这样使用采用字节数组的方法:

byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);

来自 InetAddress 的 API

主机名可以是机器名称,例如“java.sun.com”,也可以是其 IP 地址的文本表示。 如果提供了文字 IP 地址,则仅检查地址格式的有效性。

ip = InetAddress.getByAddress(new byte[] {
        (byte)192, (byte)168, (byte)0, (byte)102}
);

InetAddress.getByName 也适用于 IP 地址。

来自 JavaDoc

主机名可以是机器名称,例如“java.sun.com”,也可以是其 IP 地址的文本表示。 如果提供了文字 IP 地址,则仅检查地址格式的有效性。

api 相当容易使用。

// Lookup the dns, if the ip exists.
 if (!ip.isEmpty()) {
     InetAddress inetAddress = InetAddress.getByName(ip);
     dns = inetAddress.getCanonicalHostName(); 
 }

这是一个获取任何网站IP地址的项目,它非常有用且易于制作。

import java.net.InetAddress;
import java.net.UnkownHostExceptiin;

public class Main{
    public static void main(String[]args){
        try{
            InetAddress addr = InetAddresd.getByName("www.yahoo.com");
            System.out.println(addr.getHostAddress());

          }catch(UnknownHostException e){
             e.printStrackTrace();
        }
    }
}

InetAddress 类可用于以 IPv4 和 IPv6 格式存储 IP 地址。 您可以使用InetAddress.getByName()InetAddress.getByAddress()方法将 IP 地址存储到对象。

在以下代码片段中,我使用InetAddress.getByName()方法来存储 IPv4 和 IPv6 地址。

InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");

您还可以使用InetAddress.getByAddress()通过提供字节数组来创建对象。

InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});

此外,您可以使用InetAddress.getLoopbackAddress()获取本地地址,使用InetAddress.getLocalHost()获取使用机器名称注册的地址。

InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>

注意 - 确保通过 try/catch 包围您的代码,因为InetAddress方法返回java.net.UnknownHostException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM