博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何使用InetAddress在Java中获取IP地址
阅读量:2532 次
发布时间:2019-05-11

本文共 2116 字,大约阅读时间需要 7 分钟。

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, the InetAddress class 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 java.net.UnknownHostException;import java.net.InetAddress;public class JavaIPAddress {    /**     * @param args     * @throws UnknownHostException      */    public static void main(String[] args) throws UnknownHostException {        //print localhost ip address        System.out.println(InetAddress.getLocalHost().getHostAddress());        //print website ip address        System.out.println(InetAddress.getByName("www.journaldev.com"));        //print all ip addresses for a website        InetAddress[] inetAddresses = InetAddress.getAllByName("www.google.com");        for(InetAddress inet : inetAddresses){            System.out.println(inet);        }    }}

Output of the above program is:

上面程序的输出是:

192.168.3.1www.journaldev.com/50.116.65.160www.google.com/74.125.224.82www.google.com/74.125.224.81www.google.com/74.125.224.80www.google.com/74.125.224.83www.google.com/74.125.224.84www.google.com/2001:4860:4001:803:0:0:0:1010

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

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

These methods throw UnknownHostException if 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之类的协议来提供主机名输入。

翻译自:

转载地址:http://fumzd.baihongyu.com/

你可能感兴趣的文章
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>