下面列出了java.net.InetAddress#isAnyLocalAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String getResolvedAddress(InetSocketAddress address) {
address = NetUtils.getConnectAddress(address);
StringBuilder sb = new StringBuilder();
InetAddress resolved = address.getAddress();
if (resolved == null || resolved.isAnyLocalAddress() ||
resolved.isLoopbackAddress()) {
String lh = address.getHostName();
try {
lh = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
//Ignore and fallback.
}
sb.append(lh);
} else {
sb.append(address.getHostName());
}
sb.append(":").append(address.getPort());
return sb.toString();
}
/** Sorts an address by preference. This way code like publishing can just pick the first one */
static int sortKey(InetAddress address, boolean prefer_v6) {
int key = address.getAddress().length;
if (prefer_v6) {
key = -key;
}
if (address.isAnyLocalAddress()) {
key += 5;
}
if (address.isMulticastAddress()) {
key += 4;
}
if (address.isLoopbackAddress()) {
key += 3;
}
if (address.isLinkLocalAddress()) {
key += 2;
}
if (address.isSiteLocalAddress()) {
key += 1;
}
return key;
}
public HTTPSession(TempFileManager tempFileManager,
InputStream inputStream, OutputStream outputStream,
InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
this.outputStream = outputStream;
String remoteIp = inetAddress.isLoopbackAddress()
|| inetAddress.isAnyLocalAddress() ? "127.0.0.1"
: inetAddress.getHostAddress();
headers = new HashMap<>();
headers.put("remote-addr", remoteIp);
headers.put("http-client-ip", remoteIp);
}
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
this.outputStream = outputStream;
String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
headers = new HashMap<String, String>();
headers.put("remote-addr", remoteIp);
headers.put("http-client-ip", remoteIp);
}
public HTTPSession(NanoHTTPD httpd, ITempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.httpd = httpd;
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
this.headers = new HashMap<String, String>();
}
public static String filterIP(final InetAddress inetAddress)
{
try
{
final String ipVersion;
if (inetAddress instanceof Inet4Address)
ipVersion = "ipv4";
else if (inetAddress instanceof Inet6Address)
ipVersion = "ipv6";
else
ipVersion = "ipv?";
if (inetAddress.isAnyLocalAddress())
return "wildcard";
if (inetAddress.isSiteLocalAddress())
return "site_local_" + ipVersion;
if (inetAddress.isLinkLocalAddress())
return "link_local_" + ipVersion;
if (inetAddress.isLoopbackAddress())
return "loopback_" + ipVersion;
return inetAddress.getHostAddress();
}
catch (final IllegalArgumentException e)
{
return "illegal_ip";
}
}
/**
* Given an InetAddress, checks to see if the address is a local address, by
* comparing the address with all the interfaces on the node.
* @param addr address to check if it is local node's address
* @return true if the address corresponds to the local node
*/
public static boolean isLocalAddress(InetAddress addr) {
// Check if the address is any local or loop back
boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
// Check if the address is defined on any interface
if (!local) {
try {
local = NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
local = false;
}
}
return local;
}
public void setLocalHost(InetAddress localHost) throws SocketException {
if (localHost.isAnyLocalAddress() ||
localHost.isLoopbackAddress() ||
NetworkInterface.getByInetAddress(localHost) != null)
{
this.localHost = localHost;
} else
{
throw new IllegalArgumentException("Must be address of a local adapter");
}
}
public static boolean isGlobalUnicast(InetAddress addr)
{
// local identification block
if(addr instanceof Inet4Address && addr.getAddress()[0] == 0)
return false;
// this would be rejected by a socket with broadcast disabled anyway, but filter it to reduce exceptions
if(addr instanceof Inet4Address && java.util.Arrays.equals(addr.getAddress(), LOCAL_BROADCAST))
return false;
if(addr instanceof Inet6Address && (addr.getAddress()[0] & 0xfe) == 0xfc) // fc00::/7
return false;
if(addr instanceof Inet6Address && (V4_MAPPED.contains(addr) || V4_COMPAT.contains(addr)))
return false;
return !(addr.isAnyLocalAddress() || addr.isLinkLocalAddress() || addr.isLoopbackAddress() || addr.isMulticastAddress() || addr.isSiteLocalAddress());
}
private void checkAddress(String address, boolean allow_local) throws IllegalArgumentException, UnknownHostException {
if (address != null)
address = address.trim();
if (TextUtils.isEmpty(address))
throw new IllegalArgumentException("Bad address");
if (!Util.isNumericAddress(address))
throw new IllegalArgumentException("Bad address");
if (!allow_local) {
InetAddress iaddr = InetAddress.getByName(address);
if (iaddr.isLoopbackAddress() || iaddr.isAnyLocalAddress())
throw new IllegalArgumentException("Bad address");
}
}
public static boolean isLocalAddress(InetAddress addr) {
// Check if the address is any local or loop back
boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
// Check if the address is defined on any interface
if (!local) {
try {
local = NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
local = false;
}
}
return local;
}
private static boolean isLocalAddress(InetAddress addr) {
// Check if the address is any local or loop back
boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
// Check if the address is defined on any interface
if (!local) {
try {
local = NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
local = false;
}
}
return local;
}
private String getUrlContents(String urlString, boolean rejectLocal, boolean rejectRedirect) throws IOException {
LOGGER.trace("fetching URL contents");
URL url = new URL(urlString);
if(rejectLocal) {
InetAddress inetAddress = InetAddress.getByName(url.getHost());
if(inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress()) {
throw new IOException("Only accepts http/https protocol");
}
}
final CloseableHttpClient httpClient = getCarelessHttpClient(rejectRedirect);
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder
.setConnectTimeout(5000)
.setSocketTimeout(5000);
HttpGet getMethod = new HttpGet(urlString);
getMethod.setConfig(requestBuilder.build());
getMethod.setHeader("Accept", "application/json, */*");
if (httpClient != null) {
final CloseableHttpResponse response = httpClient.execute(getMethod);
try {
HttpEntity entity = response.getEntity();
StatusLine line = response.getStatusLine();
if(line.getStatusCode() > 299 || line.getStatusCode() < 200) {
throw new IOException("failed to read swagger with code " + line.getStatusCode());
}
return EntityUtils.toString(entity, "UTF-8");
} finally {
response.close();
httpClient.close();
}
} else {
throw new IOException("CloseableHttpClient could not be initialized");
}
}
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
this.outputStream = outputStream;
String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
headers = new HashMap<>();
headers.put("remote-addr", remoteIp);
headers.put("http-client-ip", remoteIp);
}
/**
* Determines whether the given address is a "useful" unicast address.
*
* Site local is allowed. Loopback is not.
*/
public static boolean isUnicastAddress(@CheckForNull InetAddress address) {
return (address != null)
&& !address.isAnyLocalAddress()
&& !address.isLoopbackAddress()
&& !address.isMulticastAddress();
}
private void checkAddress(String address, boolean allow_local) throws IllegalArgumentException, UnknownHostException {
if (address != null)
address = address.trim();
if (TextUtils.isEmpty(address))
throw new IllegalArgumentException("Bad address");
if (!Util.isNumericAddress(address))
throw new IllegalArgumentException("Bad address");
if (!allow_local) {
InetAddress iaddr = InetAddress.getByName(address);
if (iaddr.isLoopbackAddress() || iaddr.isAnyLocalAddress())
throw new IllegalArgumentException("Bad address");
}
}
/**
* 获取当前系统连接网络的网卡的mac地址
*
* @return
*/
public static final String getMac() {
byte[] mac = null;
StringBuffer sb = new StringBuffer();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress ip = address.nextElement();
if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
continue;
if (ip.isSiteLocalAddress())
mac = ni.getHardwareAddress();
else if (!ip.isLinkLocalAddress()) {
mac = ni.getHardwareAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
sb.append(parseByte(mac[i]));
}
}else{
return "";
}
return sb.substring(0, sb.length() - 1);
}
public static boolean isLocalhost(String host) throws SocketException, UnknownHostException {
InetAddress address = InetAddress.getByName(host);
return address.isAnyLocalAddress() || address.isLoopbackAddress();
}
/**
* checks if the provided address is a global-scope ipv6 unicast address
*/
public static boolean isGlobalAddressV6(InetAddress addr) {
return addr instanceof Inet6Address && !addr.isAnyLocalAddress() && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && !addr.isMulticastAddress() && !addr.isSiteLocalAddress() && !((Inet6Address)addr).isIPv4CompatibleAddress();
}
/**
* {@inheritDoc}
*
* @return <code>address</code> if <code>address</code> is not
* {@link InetAddress#isSiteLocalAddress() site-local},
* {@link InetAddress#isLinkLocalAddress() link-local}
* or a {@link InetAddress#isAnyLocalAddress() wildcard address}.
*/
@Override
protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException {
if( !address.isSiteLocalAddress() && !address.isLinkLocalAddress() && !address.isAnyLocalAddress() )
return address;
return null;
}