在Java中创建InetAddress对象 [英] Creating InetAddress object in Java

查看:120
本文介绍了在Java中创建InetAddress对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在字符串中转换由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.

InetAddress API文档

推荐答案

您应该可以使用 getByName getByAddress


主机名可以是机器
名称,例如asjava.sun.com,或
其IP
地址的文字表示

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address



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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆