问题描述
我试图在字符串中转换由IP号或名称指定的地址(即 localhost
或 127.0.0.1
),进入 InetAdress 对象。没有构造函数,而是返回 InetAddress 的静态方法。所以,如果我得到一个主机名,这不是问题,但如果我得到IP号怎么办?有一种方法可以获得 byte [] ,但我不确定这对我有什么帮助。所有其他方法都获取主机名。
I am trying to convert an address specified by an IP number or a name, both in String (i.e. localhost
or 127.0.0.1
), into an InetAdress object. There's no constructor but rather static methods that return an InetAddress. So if I get a host name it's not a problem, but what if I get the IP number? There's one method that gets byte[] but I'm not sure how that can help me. All other methods gets the host name.
推荐答案
您应该可以使用 getByName 或 getByAddress 。
InetAddress addr = InetAddress.getByName("127.0.0.1");
采用字节数组的方法可以像这样使用:
The method that takes a byte array can be used like this:
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
这篇关于在Java中创建InetAddress对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!