下面列出了java.net.InetAddress#equals ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This utility method tries to connect to the JobManager using the InetAddress returned by
* InetAddress.getLocalHost(). The purpose of the utility is to have a final try connecting to
* the target address using the LocalHost before using the address returned.
* We do a second try because the JM might have been unavailable during the first check.
*
* @param preliminaryResult The address detected by the heuristic
* @return either the preliminaryResult or the address returned by InetAddress.getLocalHost() (if
* we are able to connect to targetAddress from there)
*/
private static InetAddress tryLocalHostBeforeReturning(
InetAddress preliminaryResult, SocketAddress targetAddress, boolean logging) throws IOException {
InetAddress localhostName = InetAddress.getLocalHost();
if (preliminaryResult.equals(localhostName)) {
// preliminary result is equal to the local host name
return preliminaryResult;
}
else if (tryToConnect(localhostName, targetAddress, AddressDetectionState.SLOW_CONNECT.getTimeout(), logging)) {
// success, we were able to use local host to connect
LOG.debug("Preferring {} (InetAddress.getLocalHost()) for local bind point over previous candidate {}",
localhostName, preliminaryResult);
return localhostName;
}
else {
// we have to make the preliminary result the final result
return preliminaryResult;
}
}
protected boolean
sameAs(
NetworkAdminNATDeviceImpl other )
{
if ( !getAddress().equals( other.getAddress()) ||
getPort() != other.getPort()){
return( false );
}
InetAddress e1 = getExternalAddress();
InetAddress e2 = other.getExternalAddress();
if ( e1 == null && e2 == null ){
return( true );
}
if ( e1 == null || e2 == null ){
return( false );
}
return( e1.equals( e2 ));
}
private static boolean isLocalHost(String hostname) throws IOException {
InetAddress remoteAddr = InetAddress.getByName(hostname);
// Retrieve all the network interfaces on this host.
Enumeration<NetworkInterface> nis =
NetworkInterface.getNetworkInterfaces();
// Walk through the network interfaces to see
// if any of them matches the client's address.
// If true, then the client's address is local.
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress localAddr = addrs.nextElement();
if (localAddr.equals(remoteAddr)) {
return true;
}
}
}
return false;
}
/**
* Checks if the <code>newIP</code> address matches the session of <code>lastIP</code> address.
*
* Usually this is only <code>true</code> if both addresses are equal by {@link InetAddress#equals(Object)}.
* This method is called to detect if a session is stolen by a 3rd party.
* There are two properties (with their default value) to modify this behavior and specify netmasks:
* <pre>
* MCR.Servlet.Session.NetMask.IPv4=255.255.255.255
* MCR.Servlet.Session.NetMask.IPv6=FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
* </pre>
*
* @param lastIP IP address from former request
* @param newIP IP address from current request
* @return
* @throws UnknownHostException if <code>lastIP</code> or <code>newIP</code> are not valid IP addresses.
*/
public static boolean isIPAddrAllowed(String lastIP, String newIP) throws UnknownHostException {
InetAddress lastIPAddress = InetAddress.getByName(lastIP);
InetAddress newIPAddress = InetAddress.getByName(newIP);
byte[] lastIPMask = decideNetmask(lastIPAddress);
byte[] newIPMask = decideNetmask(newIPAddress);
lastIPAddress = InetAddress.getByAddress(filterIPByNetmask(lastIPAddress.getAddress(), lastIPMask));
newIPAddress = InetAddress.getByAddress(filterIPByNetmask(newIPAddress.getAddress(), newIPMask));
if (lastIPAddress.equals(newIPAddress)) {
return true;
}
String hostIP = getHostIP();
InetAddress hostIPAddress = InetAddress.getByName(hostIP);
byte[] hostIPMask = decideNetmask(hostIPAddress);
hostIPAddress = InetAddress.getByAddress(filterIPByNetmask(hostIPAddress.getAddress(), hostIPMask));
return newIPAddress.equals(hostIPAddress);
}
private InetAddress getRpcAddress(InetAddress endpoint)
{
try
{
InetAddress rpcAddress = InetAddress.getByName(StorageService.instance.getRpcaddress(endpoint));
// If rpcAddress == 0.0.0.0 (i.e. bound on all addresses), returning that is not very helpful,
// so return the internal address (which is ok since "we're bound on all addresses").
// Note that after all nodes are running a version that includes CASSANDRA-5899, rpcAddress should
// never be 0.0.0.0, so this can eventually be removed.
return rpcAddress.equals(bindAll) ? endpoint : rpcAddress;
}
catch (UnknownHostException e)
{
// That should not happen, so log an error, but return the
// endpoint address since there's a good change this is right
logger.error("Problem retrieving RPC address for {}", endpoint, e);
return endpoint;
}
}
protected boolean
sameAs(
NetworkAdminNATDeviceImpl other )
{
if ( !getAddress().equals( other.getAddress()) ||
getPort() != other.getPort()){
return( false );
}
InetAddress e1 = getExternalAddress();
InetAddress e2 = other.getExternalAddress();
if ( e1 == null && e2 == null ){
return( true );
}
if ( e1 == null || e2 == null ){
return( false );
}
return( e1.equals( e2 ));
}
private static boolean isLocal(final URI uri) {
try {
final String hostName = uri.getHost();
final InetAddress address = InetAddress.getByName(hostName);
NetworkInterface nic;
if (address.isLinkLocalAddress()) {
/*
* AS7-6382 On Windows the getByInetAddress was not identifying a NIC where the address did not have the zone
* ID, this manual iteration does allow for the address to be matched.
*/
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
nic = null;
while (interfaces.hasMoreElements() && nic == null) {
NetworkInterface current = interfaces.nextElement();
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements() && nic == null) {
InetAddress currentAddress = addresses.nextElement();
if (address.equals(currentAddress)) {
nic = current;
}
}
}
} else {
nic = NetworkInterface.getByInetAddress(address);
}
return address.isLoopbackAddress() || nic != null;
} catch (Exception e) {
return false;
}
}
public void setClientAddress(@Nonnull InetAddress clientAddress) {
Preconditions.checkArgument(!AddressUtils.isZeroAddress(clientAddress), "Client address was null or zero.");
if (clientAddress.equals(this.clientAddress))
return;
Preconditions.checkState(this.clientAddress == null, "Already have a (different) client address.");
this.clientAddress = clientAddress;
setInterfaceAddressFrom(clientAddress);
}
public String getDatacenter(InetAddress endpoint)
{
if (endpoint.equals(FBUtilities.getBroadcastAddress()))
return gceRegion;
EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
if (state == null || state.getApplicationState(ApplicationState.DC) == null)
{
if (savedEndpoints == null)
savedEndpoints = SystemKeyspace.loadDcRackInfo();
if (savedEndpoints.containsKey(endpoint))
return savedEndpoints.get(endpoint).get("data_center");
return DEFAULT_DC;
}
return state.getApplicationState(ApplicationState.DC).value;
}
/**
* Record tokens being used by another node
*/
public static synchronized void updateTokens(InetAddress ep, Collection<Token> tokens)
{
if (ep.equals(FBUtilities.getBroadcastAddress()))
{
removeEndpoint(ep);
return;
}
String req = "INSERT INTO system.%s (peer, tokens) VALUES (?, ?)";
executeInternal(String.format(req, PEERS_CF), ep, tokensAsSet(tokens));
}
private String getKnownAddress(String addr) {
try {
InetAddress a = InetAddress.getByName(addr);
if (a.equals(dns1))
return "dns1";
if (a.equals(dns2))
return "dns2";
if (a.equals(vpn4) || a.equals(vpn6))
return "vpn";
} catch (UnknownHostException ignored) {
}
return addr;
}
/**
* Return the rpc address associated with an endpoint as a string.
* @param endpoint The endpoint to get rpc address for
* @return the rpc address
*/
public String getRpcaddress(InetAddress endpoint)
{
if (endpoint.equals(FBUtilities.getBroadcastAddress()))
return DatabaseDescriptor.getBroadcastRpcAddress().getHostAddress();
else if (Gossiper.instance.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.RPC_ADDRESS) == null)
return endpoint.getHostAddress();
else
return Gossiper.instance.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.RPC_ADDRESS).value;
}
/**
* Checks registry for membership of the group on the given
* network interface.
*/
MembershipKey checkMembership(InetAddress group, NetworkInterface interf,
InetAddress source)
{
if (groups != null) {
List<MembershipKeyImpl> keys = groups.get(group);
if (keys != null) {
for (MembershipKeyImpl key: keys) {
if (key.networkInterface().equals(interf)) {
// already a member to receive all packets so return
// existing key or detect conflict
if (source == null) {
if (key.sourceAddress() == null)
return key;
throw new IllegalStateException("Already a member to receive all packets");
}
// already have source-specific membership so return key
// or detect conflict
if (key.sourceAddress() == null)
throw new IllegalStateException("Already have source-specific membership");
if (source.equals(key.sourceAddress()))
return key;
}
}
}
}
return null;
}
@Override
public ChannelFuture leaveGroup(
InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source,
ChannelPromise promise) {
checkJavaVersion();
if (multicastAddress == null) {
throw new NullPointerException("multicastAddress");
}
if (networkInterface == null) {
throw new NullPointerException("networkInterface");
}
synchronized (this) {
if (memberships != null) {
List<MembershipKey> keys = memberships.get(multicastAddress);
if (keys != null) {
Iterator<MembershipKey> keyIt = keys.iterator();
while (keyIt.hasNext()) {
MembershipKey key = keyIt.next();
if (networkInterface.equals(key.networkInterface())) {
if (source == null && key.sourceAddress() == null ||
source != null && source.equals(key.sourceAddress())) {
key.drop();
keyIt.remove();
}
}
}
if (keys.isEmpty()) {
memberships.remove(multicastAddress);
}
}
}
}
promise.setSuccess();
return promise;
}
/**
* Disconnects all clients from the server with the address.
*
* @param address
* the IP address of the client.
* @param reason
* the reason for client disconnection. A <code>null</code>
* reason will have <code>"Disconnected"</code> be used as the
* reason instead.
* @return <code>true</code> if a client was disconnect, <code>false</code>
* otherwise.
*/
public final boolean disconnect(InetAddress address, String reason) {
if (address == null) {
return false;
}
boolean disconnected = false;
for (InetSocketAddress peerAddress : clients.keySet()) {
if (address.equals(peerAddress.getAddress())) {
this.disconnect(peerAddress, reason);
disconnected = true;
}
}
return disconnected;
}
private void checkAddressIsLocal(InetAddress inetAddr) throws UnknownHostException,Exception
{
for(int i = 0; i < localAddresses.size(); i++)
{
if (inetAddr.equals((InetAddress)localAddresses.get(i)))
{
return;
}
}
consolePropertyMessage("DRDA_NeedLocalHost.S", new String[] {inetAddr.getHostName(),serverSocket.getInetAddress().getHostName()});
}
public final boolean equals(InternalDistributedMember m) {
if (this == m) {
return true;
}
if (m == null) {
return false;
}
if (getPort() != m.getPort()) {
return false;
}
final InetAddress myAddr = getIpAddress();
final InetAddress otherAddr = m.getIpAddress();
// Discard null cases
if (myAddr == null && otherAddr == null) {
return true;
}
else if (myAddr == null || otherAddr == null) {
return false;
}
if(!myAddr.equals(otherAddr)) {
return false;
}
// [bruce] names are no longer transmitted in writeEssentialData and
// so cannot be used in comparing IDs
// if (this.name == null && other.name == null) {
// // do nothing
// } else if (this.name == null) {
// return -1;
// }
// else if (other.name == null) {
// return 1;
// }
// else {
// int i = this.name.compareTo(other.name);
// if (i != 0) {
// return i;
// }
// }
if (this.uniqueTag == null && m.uniqueTag == null) {
// not loners, so look at P2P view ID
if (this.vmViewId != m.vmViewId) {
return false;
} // else they're the same, so continue
} else if (this.uniqueTag == null || m.uniqueTag == null) {
return false;
}
else if (!this.uniqueTag.equals(m.uniqueTag) ){
return false;
}
// purposely avoid comparing roles
// @todo Add durableClientAttributes to compare
return true;
}
public boolean isSameRM(XAResource xares) throws XAException {
boolean isSame = false; // preset that the RMs are NOT the same
exceptionsOnXA = null;
if (conn_.agent_.loggingEnabled()) {
conn_.agent_.logWriter_.traceEntry(this, "isSameRM", xares);
}
if (conn_.isPhysicalConnClosed()) {
connectionClosedFailure();
}
if (xares instanceof com.splicemachine.db.client.net.NetXAResource) { // both are NetXAResource so check to see if this is the same RM
// remember, isSame is initialized to false
NetXAResource derbyxares = (NetXAResource) xares;
while (true) {
if (!conn_.databaseName_.equalsIgnoreCase(derbyxares.conn_.databaseName_)) {
break; // database names are not equal, not same RM
}
if (!conn_.netAgent_.server_.equalsIgnoreCase
(derbyxares.conn_.netAgent_.server_)) { // server name strings not equal, compare IP addresses
try {
// 1st convert "localhost" to actual server name
String server1 = this.processLocalHost(conn_.netAgent_.server_);
String server2 =
this.processLocalHost(derbyxares.conn_.netAgent_.server_);
// now convert the server name to ip address
InetAddress serverIP1 = InetAddress.getByName(server1);
InetAddress serverIP2 = InetAddress.getByName(server2);
if (!serverIP1.equals(serverIP2)) {
break; // server IPs are not equal, not same RM
}
} catch (UnknownHostException ue) {
break;
}
}
if (conn_.netAgent_.port_ != derbyxares.conn_.netAgent_.port_) {
break; // ports are not equal, not same RM
}
isSame = true; // everything the same, set RMs are the same
break;
}
}
if (conn_.agent_.loggingEnabled()) {
conn_.agent_.logWriter_.traceExit
(this, "isSameRM", isSame);
}
return isSame;
}
public static boolean isLocallyConnected(com.mysql.jdbc.ConnectionImpl conn) throws SQLException {
long threadId = conn.getId();
java.sql.Statement processListStmt = conn.getMetadataSafeStatement();
ResultSet rs = null;
String processHost = null;
// "inject" for tests
if (System.getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME) != null) {
processHost = System.getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME);
} else if (conn.getProperties().getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME) != null) {
processHost = conn.getProperties().getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME);
} else { // get it from server
try {
processHost = findProcessHost(threadId, processListStmt);
if (processHost == null) {
// http://bugs.mysql.com/bug.php?id=44167 - connection ids on the wire wrap at 4 bytes even though they're 64-bit numbers
conn.getLog()
.logWarn(String.format(
"Connection id %d not found in \"SHOW PROCESSLIST\", assuming 32-bit overflow, using SELECT CONNECTION_ID() instead",
threadId));
rs = processListStmt.executeQuery("SELECT CONNECTION_ID()");
if (rs.next()) {
threadId = rs.getLong(1);
processHost = findProcessHost(threadId, processListStmt);
} else {
conn.getLog().logError(
"No rows returned for statement \"SELECT CONNECTION_ID()\", local connection check will most likely be incorrect");
}
}
} finally {
processListStmt.close();
}
}
if (processHost != null) {
conn.getLog().logDebug(String.format("Using 'host' value of '%s' to determine locality of connection", processHost));
int endIndex = processHost.lastIndexOf(":");
if (endIndex != -1) {
processHost = processHost.substring(0, endIndex);
try {
boolean isLocal = false;
InetAddress[] allHostAddr = InetAddress.getAllByName(processHost);
// mysqlConnection should be the raw socket
SocketAddress remoteSocketAddr = conn.getIO().mysqlConnection.getRemoteSocketAddress();
if (remoteSocketAddr instanceof InetSocketAddress) {
InetAddress whereIConnectedTo = ((InetSocketAddress) remoteSocketAddr).getAddress();
for (InetAddress hostAddr : allHostAddr) {
if (hostAddr.equals(whereIConnectedTo)) {
conn.getLog().logDebug(
String.format("Locally connected - HostAddress(%s).equals(whereIconnectedTo({%s})", hostAddr, whereIConnectedTo));
isLocal = true;
break;
}
conn.getLog()
.logDebug(String.format("Attempted locally connected check failed - ! HostAddress(%s).equals(whereIconnectedTo(%s)",
hostAddr, whereIConnectedTo));
}
} else {
String msg = String.format("Remote socket address %s is not an inet socket address", remoteSocketAddr);
conn.getLog().logDebug(msg);
}
return isLocal;
} catch (UnknownHostException e) {
conn.getLog().logWarn(Messages.getString("Connection.CantDetectLocalConnect", new Object[] { processHost }), e);
return false;
}
}
conn.getLog().logWarn(String
.format("No port number present in 'host' from SHOW PROCESSLIST '%s', unable to determine whether locally connected", processHost));
return false;
}
conn.getLog().logWarn(String
.format("Cannot find process listing for connection %d in SHOW PROCESSLIST output, unable to determine if locally connected", threadId));
return false;
}
protected void
check(
ClientInstance instance )
{
if ( instance == my_instance ){
return;
}
InetAddress my_ext = my_instance.getExternalAddress();
InetAddress other_ext = instance.getExternalAddress();
if ( my_ext.isLoopbackAddress() ||
other_ext.isLoopbackAddress() ||
my_ext.equals( other_ext )){
String warning = null;
int my_tcp = my_instance.getTCPListenPort();
if ( my_tcp != 0 && my_tcp != last_warned_tcp && my_tcp == instance.getTCPListenPort()){
warning = "TCP " + my_tcp;
last_warned_tcp = my_tcp;
}
int my_udp = my_instance.getUDPListenPort();
int my_udp2 = my_instance.getUDPNonDataListenPort();
int other_udp = instance.getUDPListenPort();
int other_udp2 = instance.getUDPNonDataListenPort();
if ( my_udp != 0 && my_udp != last_warned_udp && ( my_udp == other_udp || my_udp == other_udp2 )){
warning = (warning==null?"":(warning + ", ")) + "UDP " + my_udp;
last_warned_udp = my_udp;
}
if ( my_udp != my_udp2 && my_udp2 != 0 && my_udp2 != last_warned_udp2 && ( my_udp2 == other_udp || my_udp2 == other_udp2 )){
warning = (warning==null?"":(warning + ", ")) + "UDP " + my_udp2;
last_warned_udp2 = my_udp2;
}
if ( warning != null ){
Logger.logTextResource(
new LogAlert(true, LogAlert.AT_WARNING,"azinstancehandler.alert.portclash"),
new String[]{
warning,
String.valueOf(RandomUtils.LISTEN_PORT_MIN ),
String.valueOf(RandomUtils.LISTEN_PORT_MAX)});
}
}
}