1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 如何使用InetAddress在Java中获取IP地址

如何使用InetAddress在Java中获取IP地址

时间:2023-01-31 16:15:46

相关推荐

如何使用InetAddress在Java中获取IP地址

An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. In Java, theInetAddressclass represents an Internet Protocol (IP) address.

IP地址是IP使用的32位或128位无符号数字,IP是在其上构建UDP和TCP等协议的较低级别协议。 在Java中,InetAddress类表示Internet协议(IP)地址。

Here we will learn how to get localhost IP address and a website IP addresses in java using InetAddress.

在这里,我们将学习如何使用InetAddress在Java中获取本地主机IP地址和网站IP地址。

package com.journaldev.util;import .UnknownHostException;import .InetAddress;public class JavaIPAddress {/*** @param args* @throws UnknownHostException */public static void main(String[] args) throws UnknownHostException {//print localhost ip addressSystem.out.println(InetAddress.getLocalHost().getHostAddress());//print website ip addressSystem.out.println(InetAddress.getByName(""));//print all ip addresses for a websiteInetAddress[] inetAddresses = InetAddress.getAllByName("");for(InetAddress inet : inetAddresses){System.out.println(inet);}}}

Output of the above program is:

上面程序的输出是:

192.168.3./50.116.65./74.125.224./74.125.224./74.125.224./74.125.224./74.125.224./2001:4860:4001:803:0:0:0:1010

When we useInetAddress.getByName(String host)it returns the current IPv4 address of the hostname, when we useInetAddress.getAllByName(String host)it returns all the IP addresses associated with the hostname. The last output of IP is IPv6 format IP address.

当我们使用InetAddress.getByName(String host)它返回主机名的当前IPv4地址,当我们使用InetAddress.getAllByName(String host)它返回与主机名关联的所有IP地址。 IP的最后输出是IPv6格式的IP地址。

These methods throwUnknownHostExceptionif there are no IP addresses associated with the hostname. Note that we should not use any protocol like HTTP to provide the hostname input.

如果没有与主机名关联的IP地址,则这些方法将引发UnknownHostException。 请注意,我们不应使用HTTP之类的协议来提供主机名输入。

翻译自: /735/how-to-get-ip-address-in-java-using-inetaddress

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。