@POST
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Path("/natcheck")
  public VdcNatCheckResponse checkIfBehindNat(
      VdcNatCheckParam checkParam, @HeaderParam("X-Forwarded-For") String clientIp) {
    if (checkParam == null) {
      log.error("checkParam is null, X-Forwarded-For is {}", clientIp);
      throw GeoException.fatals.invalidNatCheckCall("(null)", clientIp);
    }

    String ipv4Str = checkParam.getIPv4Address();
    String ipv6Str = checkParam.getIPv6Address();
    log.info(
        String.format(
            "Performing NAT check, client address connecting to VIP: %s. Client reports its IPv4 = %s, IPv6 = %s",
            clientIp, ipv4Str, ipv6Str));

    InetAddress ipv4Addr = parseInetAddress(ipv4Str);
    InetAddress ipv6Addr = parseInetAddress(ipv6Str);
    InetAddress directAddr = parseInetAddress(clientIp);
    if (directAddr == null || ipv4Addr == null && ipv6Addr == null) {
      String ipAddrsStr = Strings.join("|", ipv4Str, ipv6Addr);
      log.error("checkParam is {}, X-Forwarded-For is {}", ipAddrsStr, clientIp);
      throw GeoException.fatals.invalidNatCheckCall(ipAddrsStr, clientIp);
    }

    VdcNatCheckResponse resp = new VdcNatCheckResponse();
    resp.setSeenIp(clientIp);
    resp.setBehindNAT(!directAddr.equals(ipv4Addr) && !directAddr.equals(ipv6Addr));

    return resp;
  }
예제 #2
0
  public void addBootstrapToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress oldEndPoint = null;

      oldEndPoint = bootstrapTokens.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      oldEndPoint = tokenToEndPointMap.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      bootstrapTokens.inverse().remove(endpoint);
      bootstrapTokens.put(token, endpoint);
    } finally {
      lock.writeLock().unlock();
    }
  }
예제 #3
0
    @Override
    public Query rangeQuery(
        Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper) {
      failIfNotIndexed();
      InetAddress lower;
      if (lowerTerm == null) {
        lower = XInetAddressPoint.MIN_VALUE;
      } else {
        lower = parse(lowerTerm);
        if (includeLower == false) {
          if (lower.equals(XInetAddressPoint.MAX_VALUE)) {
            return new MatchNoDocsQuery();
          }
          lower = XInetAddressPoint.nextUp(lower);
        }
      }

      InetAddress upper;
      if (upperTerm == null) {
        upper = XInetAddressPoint.MAX_VALUE;
      } else {
        upper = parse(upperTerm);
        if (includeUpper == false) {
          if (upper.equals(XInetAddressPoint.MIN_VALUE)) {
            return new MatchNoDocsQuery();
          }
          upper = XInetAddressPoint.nextDown(upper);
        }
      }

      return InetAddressPoint.newRangeQuery(name(), lower, upper);
    }
예제 #4
0
  /**
   * Kick the connection on the given address and port
   *
   * @param connection
   * @throws BadParameterException
   * @throws NotFoundException
   */
  public void kickConnection(ConnectionIdentifierDTO connection)
      throws BadParameterException, NotFoundException {
    InetAddress address = null;
    try {
      address = InetAddress.getByName(connection.getAddress());
    } catch (Exception e) {
      throw new BadParameterException(
          "Invalid address: " + connection.getAddress() + ". " + e.getMessage(), e);
    }

    if (connection.getPort() == null || connection.getPort() < 1 || connection.getPort() > 65535) {
      throw new BadParameterException("Invalid port number: " + connection.getPort());
    }

    WorkerConnection connectionToKick = null;

    for (WorkerConnection workerConnection : workerConnections) {
      if (address.equals(workerConnection.getRemoteAddress())
          && connection.getPort().equals(workerConnection.getRemotePort())) {
        connectionToKick = workerConnection;
        break;
      }
    }

    if (connectionToKick == null) {
      throw new NotFoundException(
          "No connection found with address "
              + connection.getAddress()
              + " and port number "
              + connection.getPort());
    }

    connectionToKick.close();
    onWorkerDisconnection(connectionToKick, new Exception("Connection kicked"));
  }
  public void run() {
    Thread thisThread = Thread.currentThread();

    ControlPoint ctrlPoint = getControlPoint();

    while (deviceNotifyThread == thisThread) {
      Thread.yield();

      // Thanks for Kazuyuki Shudo (08/23/07)
      SSDPPacket packet = null;
      try {
        packet = receive();
      } catch (IOException e) {
        break;
      }

      // Thanks for Mikael Hakman (04/20/05)
      if (packet == null) continue;

      // Thanks for Inma (02/20/04)
      InetAddress maddr = getMulticastInetAddress();
      InetAddress pmaddr = packet.getHostInetAddress();
      if (maddr.equals(pmaddr) == false) {
        Debug.warning("Invalidate Multicast Recieved from IP " + maddr + " on " + pmaddr);
        continue;
      }
      // TODO Must be performed on a different Thread in order to prevent UDP packet losses.
      if (ctrlPoint != null) ctrlPoint.notifyReceived(packet);
    }
  }
예제 #6
0
  /**
   * Store an end-point to host ID mapping. Each ID must be unique, and cannot be changed after the
   * fact.
   *
   * @param hostId
   * @param endpoint
   */
  public void updateHostId(UUID hostId, InetAddress endpoint) {
    assert hostId != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress storedEp = endpointToHostIdMap.inverse().get(hostId);
      if (storedEp != null) {
        if (!storedEp.equals(endpoint) && (FailureDetector.instance.isAlive(storedEp))) {
          throw new RuntimeException(
              String.format(
                  "Host ID collision between active endpoint %s and %s (id=%s)",
                  storedEp, endpoint, hostId));
        }
      }

      UUID storedId = endpointToHostIdMap.get(endpoint);
      if ((storedId != null) && (!storedId.equals(hostId)))
        logger.warn("Changing {}'s host ID from {} to {}", endpoint, storedId, hostId);

      endpointToHostIdMap.forcePut(endpoint, hostId);
    } finally {
      lock.writeLock().unlock();
    }
  }
예제 #7
0
  /**
   * Kick all the connections with the given address
   *
   * @param address
   * @throws NotConnectedException
   * @throws NotFoundException
   */
  public void kickAddress(AddressDTO address) throws BadParameterException, NotFoundException {
    InetAddress inetAddress = null;
    try {
      inetAddress = InetAddress.getByName(address.getAddress());
    } catch (Exception e) {
      throw new BadParameterException(
          "Invalid address: " + inetAddress.getAddress() + ". " + e.getMessage(), e);
    }

    List<WorkerConnection> connectionsToKick = new ArrayList<WorkerConnection>();

    for (WorkerConnection workerConnection : workerConnections) {
      if (inetAddress.equals(workerConnection.getRemoteAddress())) {
        connectionsToKick.add(workerConnection);
      }
    }

    if (connectionsToKick.size() < 1) {
      throw new NotFoundException("No connection found with address " + inetAddress.getAddress());
    }

    for (WorkerConnection connectionToKick : connectionsToKick) {
      connectionToKick.close();
      onWorkerDisconnection(connectionToKick, new Exception("Connection kicked"));
    }
  }
예제 #8
0
  /**
   * Update progress of receiving/sending file.
   *
   * @param newProgress new progress info
   */
  public void updateProgress(ProgressInfo newProgress) {
    assert peer.equals(newProgress.peer);

    Map<String, ProgressInfo> currentFiles =
        newProgress.direction == ProgressInfo.Direction.IN ? receivingFiles : sendingFiles;
    currentFiles.put(newProgress.fileName, newProgress);
  }
예제 #9
0
  /**
   * Update token map with a set of token/endpoint pairs in normal state.
   *
   * <p>Prefer this whenever there are multiple pairs to update, as each update (whether a single or
   * multiple) is expensive (CASSANDRA-3831).
   *
   * @param endpointTokens
   */
  public void updateNormalTokens(Multimap<InetAddress, Token> endpointTokens) {
    if (endpointTokens.isEmpty()) return;

    lock.writeLock().lock();
    try {
      boolean shouldSortTokens = false;
      for (InetAddress endpoint : endpointTokens.keySet()) {
        Collection<Token> tokens = endpointTokens.get(endpoint);

        assert tokens != null && !tokens.isEmpty();

        bootstrapTokens.removeValue(endpoint);
        tokenToEndpointMap.removeValue(endpoint);
        topology.addEndpoint(endpoint);
        leavingEndpoints.remove(endpoint);
        removeFromMoving(endpoint); // also removing this endpoint from moving

        for (Token token : tokens) {
          InetAddress prev = tokenToEndpointMap.put(token, endpoint);
          if (!endpoint.equals(prev)) {
            if (prev != null)
              logger.warn("Token {} changing ownership from {} to {}", token, prev, endpoint);
            shouldSortTokens = true;
          }
        }
      }

      if (shouldSortTokens) sortedTokens = sortTokens();
    } finally {
      lock.writeLock().unlock();
    }
  }
  protected boolean update(AZOtherInstanceImpl new_inst) {
    alive_time = SystemTime.getCurrentTime();

    InetAddress new_address = new_inst.getInternalAddress();

    boolean same = true;

    if (!internal_addresses.contains(new_address)) {

      same = false;

      List new_addresses = new ArrayList(internal_addresses);

      new_addresses.add(0, new_address);

      internal_addresses = new_addresses;
    }

    same =
        same
            && external_address.equals(new_inst.external_address)
            && tcp_port == new_inst.tcp_port
            && udp_port == new_inst.udp_port;

    external_address = new_inst.external_address;
    tcp_port = new_inst.tcp_port;
    udp_port = new_inst.udp_port;

    return (!same);
  }
예제 #11
0
파일: Gossiper.java 프로젝트: Jashinta/570
  /** Start the gossiper with the generation # retrieved from the System table */
  public void start(InetAddress localEndpoint, int generationNbr) {
    localEndpoint_ = localEndpoint;
    /* Get the seeds from the config and initialize them. */
    Set<InetAddress> seedHosts = DatabaseDescriptor.getSeeds();
    for (InetAddress seed : seedHosts) {
      if (seed.equals(localEndpoint)) continue;
      seeds_.add(seed);
    }

    /* initialize the heartbeat state for this localEndpoint */
    EndpointState localState = endpointStateMap_.get(localEndpoint_);
    if (localState == null) {
      HeartBeatState hbState = new HeartBeatState(generationNbr);
      localState = new EndpointState(hbState);
      localState.isAlive(true);
      localState.isAGossiper(true);
      endpointStateMap_.put(localEndpoint_, localState);
    }

    // notify snitches that Gossiper is about to start
    DatabaseDescriptor.getEndpointSnitch().gossiperStarting();

    scheduledGossipTask =
        StorageService.scheduledTasks.scheduleWithFixedDelay(
            new GossipTask(),
            Gossiper.intervalInMillis_,
            Gossiper.intervalInMillis_,
            TimeUnit.MILLISECONDS);
  }
예제 #12
0
  protected ServerSocket createSocket(URI uri)
      throws IOException, NoSuchAlgorithmException, KeyManagementException {
    SslConnector cnn = null;
    ServerSocketFactory ssf = null;
    cnn = (SslConnector) connector;
    // An SSLContext is an environment for implementing JSSE
    // It is used to create a ServerSocketFactory
    SSLContext sslc = SSLContext.getInstance(cnn.getProtocol().toLowerCase());

    // Initialize the SSLContext to work with our key managers
    sslc.init(cnn.getKeyManagerFactory().getKeyManagers(), null, null);

    ssf = sslc.getServerSocketFactory();

    String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
    int backlog = cnn.getBacklog();
    SSLServerSocket serverSocket = null;

    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost())
        || inetAddress.isLoopbackAddress()
        || host.trim().equals("localhost")) {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog);
    } else {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog, inetAddress);
    }
    // Authenticate the client?
    serverSocket.setNeedClientAuth(cnn.isRequireClientAuthentication());
    return serverSocket;
  }
예제 #13
0
 /** Returns true if host matches the LOCALHOST. */
 public static boolean isLocalHost(Object host) {
   if (host instanceof InetAddress) {
     if (LOCALHOST.equals(host)) {
       return true;
     } else {
       //        InetAddress hostAddr = (InetAddress)host;
       try {
         Enumeration en = NetworkInterface.getNetworkInterfaces();
         while (en.hasMoreElements()) {
           NetworkInterface i = (NetworkInterface) en.nextElement();
           for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements(); ) {
             InetAddress addr = (InetAddress) en2.nextElement();
             if (host.equals(addr)) {
               return true;
             }
           }
         }
         return false;
       } catch (SocketException e) {
         throw new GemFireIOException(
             LocalizedStrings.InetAddressUtil_UNABLE_TO_QUERY_NETWORK_INTERFACE
                 .toLocalizedString(),
             e);
       }
     }
   } else {
     return isLocalHost(InetAddressUtil.toInetAddress(host.toString()));
   }
 }
예제 #14
0
  public boolean isAllowed(HttpServletRequest request) {
    boolean allowed = hostAcl.shouldAllowAll();

    if (!allowed) {
      try {
        final InetAddress remoteClient = InetAddress.getByName(request.getRemoteHost());

        for (InetAddress allowedAddress : hostAcl.getAllowedHosts()) {
          if (remoteClient.equals(allowedAddress)) {
            allowed = true;
            break;
          }
        }
      } catch (UnknownHostException uhe) {
        LOG.error(
            "Unknown host exception caught while trying to resolve host: "
                + request.getRemoteHost()
                + " Reason: "
                + uhe.getMessage(),
            uhe);
      }
    }

    return allowed;
  }
예제 #15
0
 /** Returns true if host matches the LOOPBACK (127.0.0.1). */
 public static boolean isLoopback(Object host) {
   if (host instanceof InetAddress) {
     return LOOPBACK.equals(host);
   } else {
     return isLoopback(InetAddressUtil.toInetAddress(host.toString()));
   }
 }
예제 #16
0
 public static InetAddress determineBindAddress(InetAddress destAddress) {
   ArrayList<InetAddress> removeIPv6Addresses =
       Network.removeIPv6Addresses(Network.removeLoopbackAddresses(Network.getLocalIpAddresses()));
   for (InetAddress removeIPv6Address : removeIPv6Addresses) {
     InetAddress inetAddress = null;
     try {
       Enumeration inetAddresses =
           NetworkInterface.getByInetAddress(removeIPv6Address).getInetAddresses();
       while (inetAddresses.hasMoreElements()) {
         inetAddress = (InetAddress) inetAddresses.nextElement();
         if (inetAddress.equals(destAddress)) {
           return inetAddress;
         }
       }
     } catch (SocketException e) {
       if (inetAddress != null) {
         RobotLog.v(
             String.format(
                 "socket exception while trying to get network interface of %s",
                 inetAddress.getHostAddress()));
       } else {
         RobotLog.v("exception while trying to get remote address");
       }
     }
   }
   return determineBindAddressBasedOnWifiP2pSubnet(removeIPv6Addresses, destAddress);
 }
예제 #17
0
  protected void bind() throws IOException {
    URI bind = getBindLocation();

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {
      if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog);
      } else {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
      }
      this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
      throw IOExceptionSupport.create(
          "Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
      setConnectURI(
          new URI(
              bind.getScheme(),
              bind.getUserInfo(),
              resolveHostName(bind.getHost()),
              serverSocket.getLocalPort(),
              bind.getPath(),
              bind.getQuery(),
              bind.getFragment()));
    } catch (URISyntaxException e) {
      throw IOExceptionSupport.create(e);
    }
  }
예제 #18
0
  /**
   * Gets the specific network interface according to the given address.
   *
   * @param address the address to identify the searched network interface.
   * @return the network interface with the specified address if one exists or {@code null}
   *     otherwise.
   * @throws SocketException if an error occurs while getting the network interface information.
   * @throws NullPointerException if the given interface address is invalid.
   */
  public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException {

    if (address == null) {
      throw new NullPointerException(Messages.getString("luni.68")); // $NON-NLS-1$
    }

    /*
     * get the list of interfaces, and then loop through the list. For each
     * interface loop through the associated set of internet addresses and
     * see if one matches. If so return that network interface
     */
    Enumeration<NetworkInterface> interfaces = getNetworkInterfaces();
    if (interfaces != null) {
      while (interfaces.hasMoreElements()) {
        NetworkInterface netif = interfaces.nextElement();
        /*
         * to be compatible use the raw addresses without any security
         * filtering
         */
        // Enumeration netifAddresses = netif.getInetAddresses();
        if ((netif.addresses != null) && (netif.addresses.length != 0)) {
          Enumeration<InetAddress> netifAddresses =
              (new Vector<InetAddress>(Arrays.asList(netif.addresses))).elements();
          if (netifAddresses != null) {
            while (netifAddresses.hasMoreElements()) {
              if (address.equals(netifAddresses.nextElement())) {
                return netif;
              }
            }
          }
        }
      }
    }
    return null;
  }
예제 #19
0
 /**
  * getIpInterfaceByIpAddress
  *
  * @param ipAddress a {@link java.lang.String} object.
  * @return a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
  */
 public OnmsIpInterface getIpInterfaceByIpAddress(InetAddress ipAddress) {
   for (OnmsIpInterface iface : getIpInterfaces()) {
     if (ipAddress.equals(iface.getIpAddress())) {
       return iface;
     }
   }
   return null;
 }
예제 #20
0
파일: IaAddress.java 프로젝트: jstuyts/dhcp
 private boolean equals5(IaAddress other) {
   boolean result;
   if (ipAddress == null) {
     result = other.ipAddress == null ? equals4(other) : false;
   } else {
     result = ipAddress.equals(other.ipAddress) ? equals4(other) : false;
   }
   return result;
 }
예제 #21
0
 public static String findPerson(int port, InetAddress address) {
   String name = null;
   for (Client h : threads) {
     if (port == h.port && address.equals(h.address)) {
       name = h.nama;
     }
   }
   return name;
 }
        @Override
        public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            mdnsSd.stop();

            ConnectivityManager connManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mEth = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

            NetworkInterface netInterface = null;
            // search the network interface with the ip address returned by the wifi manager
            if ((mWifi != null) && (mWifi.isConnected())) {
              WifiManager wifiManager =
                  (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
              if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddressInt = wifiInfo.getIpAddress();
                String ipAddress =
                    String.format(
                        "%d.%d.%d.%d",
                        (ipAddressInt & 0xff),
                        (ipAddressInt >> 8 & 0xff),
                        (ipAddressInt >> 16 & 0xff),
                        (ipAddressInt >> 24 & 0xff));
                try {
                  InetAddress addr = InetAddress.getByName(ipAddress);
                  Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces();
                  while (netInterface == null && intfs.hasMoreElements()) {
                    NetworkInterface intf = intfs.nextElement();
                    Enumeration<InetAddress> interfaceAddresses = intf.getInetAddresses();
                    while (netInterface == null && interfaceAddresses.hasMoreElements()) {
                      InetAddress interfaceAddr = interfaceAddresses.nextElement();
                      if (interfaceAddr.equals(addr)) {
                        netInterface = intf;
                      }
                    }
                  }
                } catch (Exception e) {
                  ARSALPrint.e(TAG, "Unable to get the wifi network interface", e);
                }
              }
            }

            // for ethernet, it's not possible to find the correct netInterface. Assume there is
            // a default route don't specify the netinterface
            if (((mWifi != null) && (mWifi.isConnected()))
                || ((mEth != null) && (mEth.isConnected()))) {
              ARSALPrint.v(TAG, "Restaring MdsnSd");
              mdnsSd.start(netInterface);
            } else {
              netDeviceServicesHmap.clear();
              broadcaster.broadcastDeviceServiceArrayUpdated();
            }
          }
        }
예제 #23
0
  /**
   * Returns true if the input is an instance of this class and if its value equals the value
   * contained in this class.
   *
   * @param o the object to compare
   * @return true if this object and the input represent the same value
   */
  public boolean equals(Object o) {
    if (!(o instanceof IPAddressAttribute)) return false;

    IPAddressAttribute other = (IPAddressAttribute) o;

    if (!address.equals(other.address)) return false;

    if (mask != null) {
      if (other.mask == null) return false;

      if (!mask.equals(other.mask)) return false;
    } else {
      if (other.mask != null) return false;
    }

    if (!range.equals(other.range)) return false;

    return true;
  }
예제 #24
0
 @Transient
 @JsonIgnore
 public OnmsIpInterface getInterfaceWithAddress(final InetAddress addr) {
   if (addr == null) return null;
   for (final OnmsIpInterface iface : getIpInterfaces()) {
     if (addr.equals(iface.getIpAddress())) {
       return iface;
     }
   }
   return null;
 }
예제 #25
0
  @Override
  public boolean isAlive(InetAddress ep) {
    if (ep.equals(Utils.getBroadcastAddress())) return true;

    EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(ep);
    // we could assert not-null, but having isAlive fail screws a node over so badly that
    // it's worth being defensive here so minor bugs don't cause disproportionate
    // badness.  (See lealone-1463 for an example).
    if (epState == null) logger.error("unknown endpoint {}", ep);
    return epState != null && epState.isAlive();
  }
예제 #26
0
  private synchronized boolean addHostAddress(InetAddress addr, String hostName) {
    if (addr == null) {
      // Address for host name could not be resolved --> add to non-local-addresses
      fNonLocalHostAddresses.add(hostName);
      return false;
    }

    // Get the host address
    String hostAddr = addr.getHostAddress();

    // Newly discovered loopback addresses are added
    // to the local host address list first
    if (!fLocalHostAddresses.containsKey(hostAddr) && addr.isLoopbackAddress()) {
      addLocalAddress(addr);
    }

    // Is it a new local host network interface (VPN)?
    if (!fLocalHostAddresses.containsKey(hostAddr)) {
      boolean added = false;
      Enumeration<NetworkInterface> interfaces = null;
      try {
        interfaces = NetworkInterface.getNetworkInterfaces();
      } catch (SocketException e) {
        /* ignored on purpose */
      }
      while (interfaces != null && interfaces.hasMoreElements() && !added) {
        NetworkInterface iface = interfaces.nextElement();
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress candidate = addresses.nextElement();
          if (candidate.equals(addr) && !fLocalHostAddresses.containsKey(hostAddr)) {
            addLocalAddress(addr);
            added = true;
            break;
          }
        }
      }
    }

    Integer entryType = fLocalHostAddresses.get(hostAddr);
    if (entryType != null) {
      // found a new name for a known local address ?
      if (!fLocalHostAddresses.containsKey(hostName)) {
        int addrtype = entryType.intValue() & (~(HOSTMAP_ADDR | HOSTMAP_CANONICALADDR));
        fLocalHostAddresses.put(hostName, Integer.valueOf(addrtype | HOSTMAP_NAME));
      }
      return true;
    }

    fNonLocalHostAddresses.add(hostName);
    fNonLocalHostAddresses.add(hostAddr);
    return false;
  }
예제 #27
0
  /** Determines if we're connected to the given host. */
  public boolean isConnectedTo(InetAddress host) {
    UDPSocketChannel[] array = _channels;

    if (_lastConnectionID == 0) return false;
    for (int i = 0; i < array.length; i++) {
      UDPSocketChannel channel = array[i];
      if (channel != null && host.equals(channel.getRemoteSocketAddress().getAddress())) {
        return true;
      }
    }
    return false;
  }
예제 #28
0
 @Override
 public boolean equals(final Object o) {
   if (this == o) {
     return true;
   }
   if (!(o instanceof Classifier)) {
     return false;
   }
   if (!super.equals(o)) {
     return false;
   }
   final Classifier that = (Classifier) o;
   return tosMask == that.tosMask
       && srcPort == that.srcPort
       && dstPort == that.dstPort
       && priority == that.priority
       && protocol == that.protocol
       && tosOverwrite == that.tosOverwrite
       && srcAddress.equals(that.srcAddress)
       && dstAddress.equals(that.dstAddress);
 }
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Peer other = (Peer) obj;
   if (address == null) {
     if (other.address != null) return false;
   } else if (!address.equals(other.address)) return false;
   if (port != other.port) return false;
   return true;
 }
예제 #30
0
  public static boolean isLocalAddress(InetAddress addr) {
    InetAddress[] addrs = getAllLocalInetAddresses();

    if (addrs != null) {
      for (InetAddress self : addrs) {
        if (self.equals(addr)) {
          return true;
        }
      }
    }
    return false;
  }