All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.gateway.utils.NetUtils Maven / Gradle / Ivy
package com.gateway.utils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gateway.constant.Constants;
import com.gateway.exception.InitErrorException;
import io.netty.channel.Channel;
public class NetUtils {
private final static Logger logger = LoggerFactory.getLogger(NetUtils.class);
/**
*
*/
private static final int MIN_PORT = 0;
/**
*
*/
private static final int MAX_PORT = 65535;
/**
* 0-65535
*
* @param port
* @return
*/
public static boolean isInvalidPort(int port) {
return port > MAX_PORT || port < MIN_PORT;
}
/**
* 0
*
* @param port
* @return
*/
public static boolean isRandomPort(int port) {
return port < 0;
}
/**
* ,+1()
*
* @param host ip
* @param port
* @return
*/
public static int getAvailablePort(String host, int port) {
if (isAnyHost(host)
|| isLocalHost(host)
|| isHostInNetworkCard(host)) {
} else {
throw new InitErrorException("The host " + host
+ " is not found in network cards, please check config");
}
if (port < MIN_PORT) {
port = Constants.DEFAULT_SERVER_PORT;
}
for (int i = port; i <= MAX_PORT; i++) {
ServerSocket ss = null;
try {
ss = new ServerSocket();
ss.bind(new InetSocketAddress(host, i));
logger.debug("ip:{} port:{" + host + "} is available" + i);
return i;
} catch (IOException e) {
// continue
logger.warn("Can't bind to address [{" + host + "}:{" + i + "}], " +
"Maybe 1) The port has been bound. " +
"2) The network card of this host is not exists or disable. " +
"3) The host is wrong.");
logger.info("Begin try next port(auto +1):{" + i + 1 + "}");
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
}
}
}
}
throw new InitErrorException("Can't bind to ANY port of " + host + ", please check config");
}
/**
*
*/
public static final String ANYHOST = "0.0.0.0";
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
/**
* IPv4
*/
public static final Pattern IPV4_PATTERN = Pattern.compile(
"^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
/**
* 127.x.x.x localhost
*
* @param host
* @return
*/
public static boolean isLocalHost(String host) {
return StringUtils.isNotBlank(host)
&& (LOCAL_IP_PATTERN.matcher(host).matches() || "localhost".equalsIgnoreCase(host));
}
/**
* 0.0.0.0
*
* @param host
* @return
*/
public static boolean isAnyHost(String host) {
return ANYHOST.equals(host);
}
/**
* IPv4 0.0.0.0
*
* @param host
* @return
*/
public static boolean isIPv4Host(String host) {
return StringUtils.isNotBlank(host)
&& IPV4_PATTERN.matcher(host).matches();
}
/**
* ()
*
* @param host
* @return
*/
private static boolean isInvalidLocalHost(String host) {
return StringUtils.isBlank(host)
|| isAnyHost(host)
|| isLocalHost(host);
}
/**
* (,IPv4)
*
* @param address InetAddress
* @return
*/
private static boolean isValidAddress(InetAddress address) {
if (address == null || address.isLoopbackAddress())
return false;
String name = address.getHostAddress();
return (name != null
&& !isAnyHost(name)
&& !isLocalHost(name)
&& isIPv4Host(name));
}
/**
*
*
* @param host
* @return
*/
public static boolean isHostInNetworkCard(String host) {
try {
InetAddress addr = InetAddress.getByName(host);
return NetworkInterface.getByInetAddress(addr) != null;
} catch (Exception e) {
return false;
}
}
/**
* IPv4
*
* @return ip
*/
public static String getLocalHost() {
InetAddress address = getLocalAddress();
return address == null ? null : address.getHostAddress();
}
/**
* ,IP,
*
* @return IP
*/
public static InetAddress getLocalAddress() {
InetAddress localAddress = null;
try {
localAddress = InetAddress.getLocalHost();
if (isValidAddress(localAddress)) {
return localAddress;
}
} catch (Throwable e) {
logger.warn("Error when retriving ip address: " + e.getMessage(), e);
}
try {
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
Enumeration addresses = network.getInetAddresses();
if (addresses != null) {
while (addresses.hasMoreElements()) {
try {
InetAddress address = addresses.nextElement();
if (isValidAddress(address)) {
return address;
}
} catch (Throwable e) {
logger.warn("Error when retriving ip address: " + e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn("Error when retriving ip address: " + e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn("Error when retriving ip address: " + e.getMessage(), e);
}
logger.error("Can't get valid host, will use 127.0.0.1 instead.");
return localAddress;
}
/**
* InetSocketAddress host:port
*
* @param address InetSocketAddress
* @return host:port
*/
public static String toAddressString(InetSocketAddress address) {
if (address == null) {
return StringUtils.EMPTY;
} else {
return toIpString(address);
}
}
/**
* ip
*
* @param address InetSocketAddress
* @return ip
*/
public static String toIpString(InetSocketAddress address) {
if (address == null) {
return null;
} else {
InetAddress inetAddress = address.getAddress();
return inetAddress == null ? address.getHostName() :
inetAddress.getHostAddress();
}
}
/**
* ip、IP
*
* @param registryIp
* @return ipIP
*/
public static String getLocalHostByRegistry(String registryIp) {
String host = null;
if (registryIp != null && registryIp.length() > 0) {
List addrs = getIpListByRegistry(registryIp);
for (int i = 0; i < addrs.size(); i++) {
InetAddress address = getLocalHostBySocket(addrs.get(i));
if (address != null) {
host = address.getHostAddress();
if (host != null && !NetUtils.isInvalidLocalHost(host)) {
return host;
}
}
}
}
if (NetUtils.isInvalidLocalHost(host)) {
host = NetUtils.getLocalHost();
}
return host;
}
/**
*
*
* @param remoteAddress
* @return
*/
private static InetAddress getLocalHostBySocket(InetSocketAddress remoteAddress) {
InetAddress host = null;
try {
//
Socket socket = new Socket();
try {
socket.connect(remoteAddress, 1000);
//
host = socket.getLocalAddress();
} finally {
try {
socket.close();
} catch (Throwable e) {
logger.warn("NetUtils getLocalHostBySocket occur Exception!", e);
}
}
} catch (Exception e) {
logger.warn("Can not connect to host {" + remoteAddress.toString() + "}, cause by :{" + e.getMessage() + "}");
}
return host;
}
/**
*
*
* @param registryIp
* @return
*/
public static List getIpListByRegistry(String registryIp) {
List ips = new ArrayList();
String defaultPort = null;
String[] srcIps = registryIp.split(",");
for (String add : srcIps) {
int a = add.indexOf("://");
if (a > -1) {
add = add.substring(a + 3); //
}
String[] s1 = add.split(":");
if (s1.length > 1) {
if (defaultPort == null && s1[1] != null && s1[1].length() > 0) {
defaultPort = s1[1];
}
ips.add(new String[]{s1[0], s1[1]}); // ip
} else {
ips.add(new String[]{s1[0], defaultPort});
}
}
List ads = new ArrayList();
for (int j = 0; j < ips.size(); j++) {
String[] ip = ips.get(j);
try {
InetSocketAddress address = new InetSocketAddress(ip[0],
Integer.parseInt(ip[1] == null ? defaultPort : ip[1]));
ads.add(address);
} catch (Exception e) {
logger.warn("NetUtils getIpListByRegistry occur Exception!", e);
}
}
return ads;
}
/**
* ip
*
* @param whitelist ,*
* @param localIP
* @return
*/
public static boolean isMatchIPByPattern(String whitelist, String localIP) {
if (StringUtils.isNotBlank(whitelist)) {
if ("*".equals(whitelist)) {
return true;
}
for (String ips : whitelist.replace(',', ';').split(";", -1)) {
try {
if (ips.contains("*")) { //
String regex = ips.trim().replace(".", "\\.").replace("*", ".*");
Pattern pattern = Pattern.compile(regex);
if (pattern.matcher(localIP).find()) {
return true;
}
} else if (!isIPv4Host(ips)) { //
String regex = ips.trim().replace(".", "\\.");
Pattern pattern = Pattern.compile(regex);
if (pattern.matcher(localIP).find()) {
return true;
}
} else {
if (ips.equals(localIP)) {
return true;
}
}
} catch (Exception e) {
logger.warn("syntax of pattern {" + ips + "} is invalid");
}
}
}
return false;
}
/**
*
*
* @param local
* @param remote
* @return
*/
public static String connectToString(InetSocketAddress local, InetSocketAddress remote) {
return toAddressString(local) + " <-> " + toAddressString(remote);
}
/**
*
*
* @param local1
* @param remote1
* @return
*/
public static String channelToString(SocketAddress local1, SocketAddress remote1) {
try {
InetSocketAddress local = (InetSocketAddress) local1;
InetSocketAddress remote = (InetSocketAddress) remote1;
return toAddressString(local) + " -> " + toAddressString(remote);
} catch (Exception e) {
return local1 + "->" + remote1;
}
}
/**
* telnet
*
* @param ip
* @param port
* @param timeout
* @return
*/
public static boolean canTelnet(String ip, int port, int timeout) {
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
return socket.isConnected();
} catch (Exception e) {
logger.warn("NetUtils canTelnet occur Exception!", e);
return false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
public static String getTransportKey(String ip, int port) {
return ip + "::" + port;
}
public static String getClientTransportKey(String protocolName, String ip, int port) {
return protocolName + "::" + ip + "::" + port;
}
public static String getTransportKey(Channel channel) {
InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
String remoteIp = NetUtils.toIpString(address);
int port = address.getPort();
return getTransportKey(remoteIp, port);
}
}