15-1.Java 网络编程之 InetAddress(InetAddress 常用静态方法、InetAddress 常用方法)

InetAddress 概述

  1. InetAddress 用于表示一个 IP 地址(IPv4 / IPv6)

  2. InetAddress 提供了获取主机名、获取 IP 地址等一系列方法

  3. 其中 Inet 是 Internet 的缩写,代表因特网


一、InetAddress 常用静态方法

1、基本介绍
方法说明
InetAddress getByName(String host)根据指定主机名 / 域名获取 InetAddress 对象
InetAddress getByAddress(byte[] addr)根据指定 IP 地址字节数组获取 InetAddress 对象
InetAddress getByAddress(String host, byte[] addr)根据指定主机名和 IP 地址字节数组获取 InetAddress 对象
InetAddress getLocalHost()获取本机的 InetAddress 对象
2、演示
  1. getByName 方法
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");

System.out.println(inetAddress);
// 输出结果

www.baidu.com/180.101.50.242
  1. getByAddress 方法
byte[] ipAddressBytes = {(byte) 192, (byte) 168, 1, 1};
InetAddress inetAddress = InetAddress.getByAddress(ipAddressBytes);

System.out.println(inetAddress);
// 输出结果

/192.168.1.1
  1. getByAddress 方法
String host = "Hello";
byte[] ipAddressBytes = {(byte) 192, (byte) 168, 1, 1};
InetAddress inetAddress = InetAddress.getByAddress(host, ipAddressBytes);

System.out.println(inetAddress);
// 输出结果

Hello/192.168.1.1
  1. getLocalHost 方法
InetAddress inetAddress = InetAddress.getLocalHost();

System.out.println(inetAddress);
// 输出结果

LAPTOP-9OPEOOBV/192.168.200.1

二、InetAddress 常用方法

1、基本介绍
方法说明
String getHostName()获取 InetAddress 对象的主机名
String getHostAddress()获取 InetAddress 对象的 IP 地址
2、演示
  1. getHostName 方法
String host = "Hello";
byte[] ipAddressBytes = {(byte) 192, (byte) 168, 1, 1};
InetAddress inetAddress = InetAddress.getByAddress(host, ipAddressBytes);

System.out.println(inetAddress.getHostName());
// 输出结果

Hello
  1. getHostAddress 方法
String host = "Hello";
byte[] ipAddressBytes = {(byte) 192, (byte) 168, 1, 1};
InetAddress inetAddress = InetAddress.getByAddress(host, ipAddressBytes);

System.out.println(inetAddress.getHostAddress());
// 输出结果

192.168.1.1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值