Java:将字符串(表示IP)转换为InetAddress [英] Java: Convert a String (representing an IP) to InetAddress
问题描述
我正在尝试将字符串(表示IP地址,例如 10.0.2.50
)转换为一个 InetAddress
obj。
I'm trying to convert a string(representing an IP address, e.g. 10.0.2.50
) into an InetAddress
obj.
根据API,可以创建一个提供表示主机名的字符串的Object(例如 www.google.ch
)。这不是我的选择,因为我没有我想要创建的每个InetAddress对象的主机名(除了它需要太长时间)。
According to the API it is possible to create an Object providing a String representing a hostname (e.g. www.google.ch
). This is not an option for me since I do not have the hostname for each InetAddress object I want to create(besides that it takes too long).
是否可以将字符串(例如 10.0.2.50
)转换为 InetAddress
obj。? (根据api,如果您的IP为 byte []
,则可以这样做,但如何转换 String
包含一个IP到 byte []
?)
Is it possible to convert a String (e.g. 10.0.2.50
) into an InetAddress
obj.? (according to the api it is possible to do so if you have the IP as byte[]
, but how do I convert a String
containing an IP into byte[]
?)
推荐答案
只需调用 InetAddress.getByName(字符串主机)
传入您的文本IP地址。
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
来自javadoc:The主机名可以是机器名,例如java.sun.com,也可以是其IP地址的文本表示。
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
这篇关于Java:将字符串(表示IP)转换为InetAddress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!