在Java中创建InetAddress对象

90

我正在尝试将一个用IP地址或名称(都是字符串,例如localhost127.0.0.1)指定的地址转换为一个InetAddress对象。没有构造函数,而是返回一个InetAddress的静态方法。如果我得到主机名,这不是问题,但如果我得到IP地址呢?有一个方法可以传入byte[],但我不确定它如何帮助我。所有其他方法都需要主机名。

InetAddress API文档

7个回答

146

你可以使用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);

5
当你有大于127的数字时,你该怎么做?例如IP地址192.168.0.1。你是对整数进行0xFF掩码处理还是将整数强制转换为字节类型? - Matej Kormuth
@MatejKormuth 我认为使用0xFF进行掩码处理应该可以。 - Bala R
1
@matej-kormuth 你也可以像Inet4AddressImpl一样表达它:byte[] loopback = {0x7f,0x00,0x00,0x01}; - Carlos Ferreyra
默认构造函数无法处理由隐式超级构造函数抛出的UnknownHostException异常类型。必须定义一个显式构造函数。 - Schütze
帮助将InetAddress的创建包含在try/catch语句中。 - MethodMan

9

来自InetAddress的API

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


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

3

这个API非常容易使用。

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

3

InetAddress.getByName也适用于IP地址。

从JavaDoc中可以看到:

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


2

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


0

这是一个获取任何网站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();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接