代码拉取完成,页面将自动刷新
package net.gdface.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.net.HostAndPort;
import com.google.common.primitives.Bytes;
import com.google.common.base.Function;
/**
* 网络管理工具类
* @author guyadong
* @since 1.0.7
*
*/
public class NetworkUtil {
public static final String DEFAULT_HOST = "localhost";
public static enum Radix{
/** 二进制 */BIN(2),
/** 十进制 */DEC(10),
/** 十六进制 */HEX(16),
/** 十六进制2字节 */HEX16(16);
public final int value;
Radix(int radix){
this.value = radix;
}
}
public static enum Filter implements Predicate<NetworkInterface>{
/** 过滤器: 所有网卡 */ALL,
/** 过滤器: 在线设备,see also {@link NetworkInterface#isUp()} */UP,
/** 过滤器: 虚拟接口,see also {@link NetworkInterface#isVirtual()} */VIRTUAL,
/** 过滤器:LOOPBACK, see also {@link NetworkInterface#isLoopback()} */LOOPBACK,
/** 过滤器:物理网卡 */PHYICAL_ONLY,
/** 过滤器:本地以太网卡 */ETH_NIC,
/** 过滤器:物理网卡(非虚拟) */NOVIRTUAL;
@Override
public boolean apply(NetworkInterface input) {
if(null == input ){
return false;
}
try{
switch(this){
case UP:
return input.isUp();
case VIRTUAL:
return input.isVirtual();
case LOOPBACK:
return input.isLoopback();
case PHYICAL_ONLY :{
byte[] hardwareAddress = input.getHardwareAddress();
return null != hardwareAddress
&& hardwareAddress.length > 0
&& !input.isVirtual()
&& !isVMMac(hardwareAddress);
}
case ETH_NIC :{
byte[] hardwareAddress = input.getHardwareAddress();
return null != hardwareAddress
&& hardwareAddress.length > 0
&& !input.isVirtual()
&& !input.isLoopback()
&& input.getInetAddresses().hasMoreElements();
}
case NOVIRTUAL :{
byte[] hardwareAddress = input.getHardwareAddress();
return null != hardwareAddress
&& hardwareAddress.length > 0
&& !input.isVirtual();
}
case ALL:
default :
return true;
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
}
/**
* 根据过滤器{@code filters}指定的条件(AND)返回网卡设备对象
* @param filters
* @return 过滤后的网卡集合
*/
@SafeVarargs
@SuppressWarnings("unchecked")
public static Set<NetworkInterface> getNICs(Predicate<NetworkInterface> ...filters) {
if(null == filters){
filters = new Predicate[]{Filter.ALL};
}
try {
Iterator<NetworkInterface> filtered = Iterators.filter(
Iterators.forEnumeration(NetworkInterface.getNetworkInterfaces()),
Predicates.and(filters));
return ImmutableSet.copyOf(filtered);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
/**
* 返回所有物理网卡
* @return 物理网卡集合
*/
public static Set<NetworkInterface> getPhysicalNICs() {
return getNICs(Filter.PHYICAL_ONLY,Filter.UP);
}
/**
* 返回所有物理(非虚拟)网卡
* @return 物理(非虚拟)网卡集合
*/
public static Set<NetworkInterface> getNoVirtualNICs() {
return getNICs(Filter.NOVIRTUAL,Filter.UP);
}
/**
* 将{@code byte[]} 转换为{@code radix}指定格式的字符串
*
* @param source
* @param separator 分隔符
* @param radix 进制基数
* @return {@code source}为{@code null}时返回空字符串
*/
public static final String format(byte[] source,String separator, final Radix radix) {
if (null == source){
return "";
}
if(null == separator){
separator = "";
}
List<String> list = Lists.transform(Bytes.asList(source),new Function<Byte,String>(){
@Override
public String apply(Byte input) {
switch (radix) {
case HEX:
case HEX16:
return String.format("%02x", input & 0xff);
default:
return Integer.toString(input & 0xff, radix.value);
}
}});
if(Radix.HEX16.equals(radix)){
return Joiner.on("").join(list).replaceAll(".{4}",separator + "$0").substring(1);
}
return Joiner.on(separator).join(list);
}
/**
* MAC地址格式(16进制)格式化{@code source}指定的字节数组
* @see #format(byte[], String, Radix)
*/
public static final String formatMac(byte[] source,String separator) {
return format(source,separator,Radix.HEX);
}
/**
* 以IP地址格式(点分位)格式化{@code source}指定的字节数组<br>
* @see #format(byte[], String, Radix)
*/
public static final String formatIp(byte[] source) {
return format(source,".",Radix.DEC);
}
/**
* 以IPV6地址格式(点分位)格式化{@code source}指定的字节数组<br>
* @see #format(byte[], String, Radix)
*/
public static final String formatIpv6(byte[] source) {
return format(source,":",Radix.HEX16);
}
/**
* 将IP地址对象格式化{@code source}指定的字符串<br>
* IPV4地址格式为'.'分隔的十进制数,如192.168.10.100
* IPV6地址格式化为':'分隔的16进制数据,如 fe80:0000:0001:0000:0440:44ff:1233:5678
* @param inetAddress
* @return 格式化的IP地址字符串
*/
public static final String formatIp(InetAddress inetAddress){
if(inetAddress instanceof Inet6Address){
return NetworkUtil.formatIpv6(inetAddress.getAddress());
}else if (inetAddress instanceof Inet4Address){
return NetworkUtil.formatIp(inetAddress.getAddress());
}
return null;
}
/**
* 返回指定{@code address}绑定的网卡的物理地址(MAC)
* @param address
* @return 指定的{@code address}没有绑定在任何网卡上返回{@code null}
* @see NetworkInterface#getByInetAddress(InetAddress)
* @see NetworkInterface#getHardwareAddress()
*/
public static byte[] getMacAddress(InetAddress address) {
try {
NetworkInterface nic = NetworkInterface.getByInetAddress(address);
return null == nic ? null : nic.getHardwareAddress();
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
/**
* @param nic 网卡对象
* @param separator 格式化分隔符
* @return 表示MAC地址的字符串
*/
public static String getMacAddress(NetworkInterface nic,String separator) {
try {
return format(nic.getHardwareAddress(),separator, Radix.HEX);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
/**
* 参见 {@link #getMacAddress(InetAddress)}
* @param address
* @param separator 格式化分隔符
* @return 表示MAC地址的字符串
*/
public static String getMacAddress(InetAddress address,String separator) {
return format(getMacAddress(address),separator, Radix.HEX);
}
private static byte invalidMacs[][] = {
/** VMWare */{0x00, 0x05, 0x69},
/** VMWare */{0x00, 0x1C, 0x14},
/** VMWare */{0x00, 0x0C, 0x29},
/** VMWare */{0x00, 0x50, 0x56},
/** Virtualbox */{0x08, 0x00, 0x27},
/** Virtualbox */{0x0A, 0x00, 0x27},
/** Virtual-PC */{0x00, 0x03, (byte)0xFF},
/** Hyper-V */{0x00, 0x15, 0x5D}
};
private static boolean isVMMac(byte[] mac) {
if(null == mac) {
return false;
}
for (byte[] invalid: invalidMacs){
if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) {
return true;
}
}
return false;
}
/** 判断{@code host}是否为localhost */
public static final boolean isLoopbackAddress(String host) {
return "127.0.0.1".equals(host)
|| "::1".equals(host)
|| DEFAULT_HOST.equals(host);
}
/** 判断{@code address}是否为本机地址 */
public static final boolean isLocalhost(InetAddress address) {
try {
return address.isLoopbackAddress()
|| InetAddress.getLocalHost().getHostAddress().equals( address.getHostAddress()) ;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
/** 判断{@code address}是否为本机地址 */
public static final boolean isLocalhost(String host) {
try {
return isLoopbackAddress(host) || isLocalhost(InetAddress.getByName(checkNotNull(host)));
} catch (UnknownHostException e) {
return false;
}
}
/** 如果{@code host}为localhost转换为{@value #DEFAULT_HOST} */
public static final String convertHost(String host) {
return isLoopbackAddress(host)? DEFAULT_HOST : host;
}
/** 遍历所有物理(非虚拟)网卡上绑定的地址,判断{@code address}是否为本机网卡绑定的地址 */
public static boolean selfBind(final InetAddress address){
if(isLocalhost(address)){
return true;
}
final Predicate<InetAddress> filter = new Predicate<InetAddress>(){
@Override
public boolean apply(InetAddress input) {
return input.getHostAddress().equals(address.getHostAddress());
}};
return Iterators.tryFind(getNoVirtualNICs().iterator(),new Predicate<NetworkInterface>(){
@Override
public boolean apply(NetworkInterface input) {
return Iterators.tryFind(
Iterators.forEnumeration(input.getInetAddresses()),
filter).isPresent();
}}).isPresent();
}
/** see also {@link #selfBind(InetAddress)} */
public static boolean selfBind(String host){
try {
return selfBind(InetAddress.getByName(host));
} catch (UnknownHostException e) {
return false;
}
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的网卡IP地址<br>
* @param host 主机名
* @param port 端口号
* @return 本机的IP地址
* @throws IOException 目标连接失败
*/
public static InetAddress getLocalIp(String host,int port) throws IOException {
Socket socket = null;
try {
socket = new Socket(host,port);
return socket.getLocalAddress();
} finally{
if(socket != null){
socket.close();
}
}
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的网卡IP地址<br>
* @param hostAndPort 用于测试连接的主机,不可为空
* @return 本机的IP地址
* @throws IOException 目标连接失败
*/
public static InetAddress getLocalIp(HostAndPort hostAndPort) throws IOException, IllegalArgumentException {
return getLocalIp(hostAndPort.getHost(), hostAndPort.getPort());
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的网卡IP地址<br>
* @param hostPortString 用于测试连接的主机(host:port format),不可为空
* @return 本机的IP地址
* @throws IOException 目标连接失败
* @throws IllegalArgumentException {@code hostPortString}格式错误,导致无法从{@code hostPortString}解析出主机名和端口号
*/
public static InetAddress getLocalIp(String hostPortString) throws IOException, IllegalArgumentException {
HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);
return getLocalIp(hostAndPort.getHost(), hostAndPort.getPort());
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的网卡IP地址<br>
* 通过(并发)对一组主机进行socket连接测试获取当前网卡的物理地址,任何一个测试通过即返回
* @param hostAndPorts 用于测试连接的主机(host:port format)列表,不可为空
* @return MAC地址字节数组
* @throws IOException 无法获取本机MAC
* @throws IllegalArgumentException {@code hostAndPorts}格式错误,导致无法从{@code hostAndPorts}解析出主机名和端口号
*/
public static InetAddress getLocalIp(String...hostAndPorts) throws IOException {
checkArgument(hostAndPorts != null && hostAndPorts.length > 0,"hostAndPorts is null or empty");
boolean hasNull = Iterables.tryFind(Arrays.asList(hostAndPorts), Predicates.isNull()).isPresent();
checkArgument(!hasNull,"has null element in hostAndPorts");
final AtomicReference<InetAddress> mac = new AtomicReference<>();
for(final String h : hostAndPorts){
new Thread(){
@Override
public void run() {
try {
InetAddress m = getLocalIp(h);
//System.out.println(h + " OK");
if(mac.compareAndSet(null, m)){
synchronized (mac) {
mac.notifyAll();
}
}
} catch (IOException e) {
// DO NOTHING
}
}
}.start();
}
try {
synchronized (mac) {
// 等待线程结束返回
mac.wait(20*1000);
}
if(null == mac.get()){
throw new IOException("ALL HOSTS CAN'T BE CONNECTED, FAIL TO get current mac");
}
return mac.get();
} catch (InterruptedException e) {
}
throw new IOException("FAIL TO get current mac");
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的当前网卡物理地址
* @param host 主机名
* @param port 端口号
* @return MAC地址字节数组
* @throws IOException
*/
public static byte[] getCurrentMac(String host,int port) throws IOException {
InetAddress address = getLocalIp(host,port);
NetworkInterface nic = NetworkInterface.getByInetAddress(address);
return nic.getHardwareAddress();
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的当前网卡物理地址
* @param hostAndPort 用于测试连接的主机,不可为空
* @return MAC地址字节数组
* @throws IOException 目标连接失败
*/
public static byte[] getCurrentMac(HostAndPort hostAndPort) throws IOException {
return getCurrentMac(hostAndPort.getHost(),hostAndPort.getPort());
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的当前网卡物理地址
* @param hostPortString 用于测试连接的主机(host:port format),不可为空
* @return MAC地址字节数组
* @throws IOException 目标连接失败
* @throws IllegalArgumentException {@code hostPortString}格式错误,导致无法从{@code hostPortString}解析出主机名和端口号
*/
public static byte[] getCurrentMac(String hostPortString) throws IOException {
HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);
return getCurrentMac(hostAndPort.getHost(),hostAndPort.getPort());
}
/**
* 通过尝试建立socket连接(tcp)的方式获取访问指定host的当前网卡物理地址<br>
* 通过(并发)对一组主机进行socket连接测试获取当前网卡的物理地址,任何一个测试通过即返回
* @param hostAndPorts 用于测试连接的主机(host:port format)列表,不可为空
* @return MAC地址字节数组
* @throws IOException 无法获取本机MAC
* @throws IllegalArgumentException {@code hostAndPorts}格式错误,导致无法从{@code hostAndPorts}解析出主机名和端口号
*/
public static byte[] getCurrentMac(String...hostAndPorts) throws IOException {
InetAddress address = getLocalIp(hostAndPorts);
NetworkInterface nic = NetworkInterface.getByInetAddress(address);
return nic.getHardwareAddress();
}
/**
* 向指定的url发送http请求
* @param url
* @param requestType 请求类型,see {@link HttpURLConnection#setRequestMethod(String)}
* @return 返回响应数据,请求失败返回{@code null}
*/
public static String sendHttpRequest(URL url,String requestType) {
HttpURLConnection con = null;
BufferedReader buffer = null;
StringBuffer resultBuffer = null;
try {
//得到连接对象
con = (HttpURLConnection) url.openConnection();
//设置请求类型
con.setRequestMethod(requestType);
//设置请求需要返回的数据类型和字符集类型
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//允许写出
con.setDoOutput(true);
//允许读入
con.setDoInput(true);
//不使用缓存
con.setUseCaches(false);
//得到响应码
int responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = con.getInputStream();
//将响应流转换成字符串
resultBuffer = new StringBuffer();
String line;
buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = buffer.readLine()) != null) {
resultBuffer.append(line);
}
return resultBuffer.toString();
}
}catch(Exception e) {
}finally {
if (con != null){
con.disconnect();
}
}
return null;
}
/**
* 连接测试返回状态
* @author guyadong
*
*/
public static enum ConnectStatus{
/** 可连接,http响应有效 */CONNECTABLE,
/** 可连接,http响应无效 */INVALID_RESPONE,
/** 连接失败 */FAIL
}
/**
* 测试http连接是否可连接<br>
* 连接失败返回{@link ConnectStatus#FAIL},
* 建立连接后用
* {@code responseValidator}验证响应数据,{@code responseValidator}返回{@code true}则连接有效返回{@link ConnectStatus#CONNECTABLE},
* {@code responseValidator}返回{@code false}则连接无效返回{@link ConnectStatus#INVALID_RESPONE} ,
*
* @param url 测试的url
* @param responseValidator 用于验证响应数据是否有效的验证器,
* 为{@code null}时,只要连接成功就返回{@link ConnectStatus#CONNECTABLE}
* @return 连接状态{@link ConnectStatus}
*/
public static ConnectStatus testHttpConnect(URL url,Predicate<String> responseValidator){
String reponse = sendHttpRequest(url,"GET");
responseValidator = MoreObjects.firstNonNull(responseValidator, Predicates.<String>alwaysTrue());
return reponse == null
? ConnectStatus.FAIL :
(responseValidator.apply(reponse)
? ConnectStatus.CONNECTABLE : ConnectStatus.INVALID_RESPONE);
}
/**
* 测试http连接是否可连接
* @param url 测试的url
* @param responseValidator
* @return 连接状态{@link ConnectStatus}
* @see #testHttpConnect(URL, Predicate)
*/
public static ConnectStatus testHttpConnect(String url,Predicate<String> responseValidator){
try {
return testHttpConnect(new URL(url),responseValidator);
} catch (Exception e) {
return ConnectStatus.FAIL;
}
}
/**
* 测试HTTP连接是否可连接
* @param host 主机名
* @param port 端口号
* @param responseValidator
* @return 连接状态{@link ConnectStatus}
* @see #testHttpConnect(URL, Predicate)
*/
public static ConnectStatus testHttpConnect(String host,int port,Predicate<String> responseValidator){
try {
return testHttpConnect(new URL("http",host,port,""), responseValidator);
} catch (Exception e) {
return ConnectStatus.FAIL;
}
}
/**
* 测试http连接是否可连接
* @param url
* @param responseValidator
* @return 连接成功{@link ConnectStatus#CONNECTABLE}返回{@code true},
* 连接失败{@link ConnectStatus#FAIL}返回{@code false}
* 响应无效{@link ConnectStatus#INVALID_RESPONE}抛出异常
* @see #testHttpConnect(URL, Predicate)
* @throws IllegalStateException 连接响应无效
*/
public static boolean testHttpConnectChecked(URL url,Predicate<String> responseValidator){
ConnectStatus status = testHttpConnect(url,responseValidator);
checkState(status != ConnectStatus.INVALID_RESPONE,"INVALID INVALID_RESPONE from %s",url);
return status == ConnectStatus.CONNECTABLE;
}
/**
* 测试http连接是否可连接
* @param url
* @param responseValidator
* @return HTTP连接可连接返回{@code true},否则返回{@code false}
* @see #testHttpConnectChecked(URL, Predicate)
* @throws IllegalStateException 连接响应无效,连接状态为 {@link ConnectStatus#INVALID_RESPONE}时
*/
public static boolean testHttpConnectChecked(String url,Predicate<String> responseValidator){
try {
return testHttpConnectChecked(new URL(url),responseValidator);
} catch (Exception e) {
return false;
}
}
/**
* 测试HTTP连接是否可连接
* @param host
* @param port
* @param responseValidator
* @return HTTP连接可连接返回{@code true},否则返回{@code false}
* @see #testHttpConnectChecked(URL, Predicate)
* @throws IllegalStateException 连接响应无效,连接状态为 {@link ConnectStatus#INVALID_RESPONE}时
*/
public static boolean testHttpConnectChecked(String host,int port,Predicate<String> responseValidator){
try {
return testHttpConnectChecked(new URL("http",host,port,""), responseValidator);
} catch (Exception e) {
return false;
}
}
/**
* 验证MAC地址有效性
* @throws IllegalArgumentException MAC地址无效
*/
public static final byte[] validateMac(byte[]mac){
checkArgument(null != mac && 6 == mac.length ,"INVAILD MAC address");
return mac;
}
/**
* 向指定的组播或广播地址和端口发送组播数据
* @param group 组播或广播地址
* @param port 端口
* @param message 发送的数据
* @param ttl time-to-live for multicast packets
* @param nic 指定发送数据的网卡
* @throws IOException
*/
public static void sendMulticast(InetAddress group,int port,byte[] message, Integer ttl,NetworkInterface nic) throws IOException{
checkArgument(null != group,"group is null");
checkArgument(group.isMulticastAddress() || isBroadcast(group),"group %s is not a multicast or broadcast address",group);
checkArgument(message != null && message.length > 0,"message is null or empty");
checkArgument(null != nic,"nic is null");
Iterator<InetAddress> nifAddresses = Iterators.filter(Iterators.forEnumeration(nic.getInetAddresses()),Predicates.and(FILTER_IPV4,FILTER_NOT_LINK_LOCAL));
if(!nifAddresses.hasNext()){
//System.out.printf("NOT IPV4 ADDRESS ON %s\n",nic.toString());
return;
}
InetSocketAddress inetAddr= new InetSocketAddress(nifAddresses.next(),0);
DatagramSocket ds = null;
try {
if(group.isMulticastAddress()){
@SuppressWarnings("resource")
MulticastSocket ms = new MulticastSocket(inetAddr);
if(ttl != null){
ms.setTimeToLive(ttl);
}
ds = ms;
}else{
ds = new DatagramSocket(inetAddr);
ds.setBroadcast(true);
}
ds.send(new DatagramPacket(message, message.length,group,port));
} finally {
if(ds != null){
ds.close();
}
}
}
/**
* 向指定的组播或广播地址和端口发送组播数据
* @param group 组播或广播地址
* @param port 端口
* @param message 发送的数据
* @param ttl time-to-live for multicast packets
* @throws IOException
*/
public static void sendMulticast(InetAddress group,int port,byte[] message, Integer ttl) throws IOException{
checkArgument(null != group,"group is null");
checkArgument(group.isMulticastAddress() || isBroadcast(group),"group %s is not a multicast or broadcast address",group);
checkArgument(message != null && message.length > 0,"message is null or empty");
int count = 0;
IOException last = null;
Set<NetworkInterface> ethNICs = getNICs(Filter.UP,Filter.ETH_NIC);
if(ethNICs.isEmpty()){
// 没有找到以太网卡抛出异常
throw new IOException("NOT FOUND ETHERNET NIC");
}
for(NetworkInterface nic:ethNICs){
try {
sendMulticast(group,port,message,ttl,nic);
count ++;
} catch (IOException e) {
// System.out.printf("%s SEND ERROR:%s\n", nic,e.toString());
last = e;
}
}
if(count == 0){
// 如果没有成功发送一次,则抛出异常
throw new IOException("FAIL TO SEND multicast/broadcast Datagram to " + group + ":" + port + " ON ALL NICS", last);
}
}
/**
* 向指定的组播或广播地址和端口发送组播数据
* @param bindaddr 组播IP地址
* @param port 端口
* @param message
* @throws IOException
*/
public static void sendMulticast(String bindaddr,int port,byte[] message) throws IOException{
checkArgument(!Strings.isNullOrEmpty(bindaddr),"bindaddr is null or empty");
sendMulticast(InetAddress.getByName(bindaddr),port,message, null);
}
/**
* 向指定的组播或广播地址和端口发送组播数据
* @param hostPort 组播地址和端口号(:号分隔) 如:244.12.12.12:4331,或[244.12.12.12:4331]
* @param message
* @throws IOException
*/
public static void sendMulticast(String hostPort,byte[] message) throws IOException{
HostAndPort hostAndPort = HostAndPort.fromString(hostPort);
sendMulticast(InetAddress.getByName(hostAndPort.getHost()),hostAndPort.getPort(),message, null);
}
public static final Predicate<InetAddress> FILTER_IPV4 = new Predicate<InetAddress>() {
@Override
public boolean apply(InetAddress addr) {
return addr instanceof Inet4Address;
}
};
public static final Predicate<InetAddress> FILTER_NOT_LINK_LOCAL = new Predicate<InetAddress>() {
@Override
public boolean apply(InetAddress addr) {
return !addr.isLinkLocalAddress();
}
};
/**
* 返回所有物理网卡绑定的IP(ipv4)地址
* @return IP地址集合
*/
public static Set<InetAddress> ipv4AddressesOfPhysicalNICs() {
return addressesOfPhysicalNICs(FILTER_IPV4,FILTER_NOT_LINK_LOCAL);
}
/**
* 根据过滤器(filter)指定的规则返回符合要求的所有物理网卡的IP地址
* @param filters
* @return 过滤后的IP地址集合
*/
@SafeVarargs
@SuppressWarnings("unchecked")
public static Set<InetAddress> addressesOfPhysicalNICs(Predicate<InetAddress>... filters) {
filters = MoreObjects.firstNonNull(filters, new Predicate[]{});
final Set<InetAddress> sets = Sets.newHashSet();
for(NetworkInterface nic:NetworkUtil.getPhysicalNICs()){
Iterator<InetAddress> itor = Iterators.filter(Iterators.forEnumeration(nic.getInetAddresses()),
Predicates.and(filters));
sets.addAll(Sets.newHashSet(itor));
}
return sets;
}
/**
* 返回所有物理(非虚拟)网卡绑定的IP(ipv4)地址
* @return IP(ipv4)地址集合
*/
public static Set<InetAddress> ipv4AddressesOfNoVirtualNICs() {
return addressesOfNoVirtualNICs(FILTER_IPV4,FILTER_NOT_LINK_LOCAL);
}
/**
* 根据过滤器(filter)指定的规则返回符合要求的所有物理(非虚拟)网卡的IP地址
* @param filters
* @return 过滤后的IP地址集合
*/
@SafeVarargs
@SuppressWarnings("unchecked")
public static Set<InetAddress> addressesOfNoVirtualNICs(Predicate<InetAddress>... filters) {
filters = MoreObjects.firstNonNull(filters, new Predicate[]{});
final Set<InetAddress> sets = Sets.newHashSet();
for(NetworkInterface nic:NetworkUtil.getNoVirtualNICs()){
Iterator<InetAddress> itor = Iterators.filter(Iterators.forEnumeration(nic.getInetAddresses()),
Predicates.and(filters));
sets.addAll(Sets.newHashSet(itor));
}
return sets;
}
public static boolean isReachable(String address, int port, int timeoutMillis) {
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(address, port), timeoutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
/**
* 判断一个地址是否为广播地址(255.255.255.255)
* @param addr
* @return addr为广播地址返回{@code true},否则返回{@code false}
*/
public static boolean isBroadcast(InetAddress addr){
return addr.getHostAddress().equals("255.255.255.255");
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。