Пример #1
2
 private final void socketrun() {
   do {
     if (link.socketport != 0) {
       try {
         Socket socket =
             new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport);
         socket.setSoTimeout(30000);
         socket.setTcpNoDelay(true);
         link.s = socket;
       } catch (Exception _ex) {
         link.s = null;
       }
       link.socketport = 0;
     }
     if (link.runme != null) {
       Thread thread = new Thread(link.runme);
       thread.setDaemon(true);
       thread.start();
       link.runme = null;
     }
     if (link.iplookup != null) {
       String s = "unknown";
       try {
         s = InetAddress.getByName(link.iplookup).getHostName();
       } catch (Exception _ex) {
       }
       link.host = s;
       link.iplookup = null;
     }
     try {
       Thread.sleep(100L);
     } catch (Exception _ex) {
     }
   } while (true);
 }
Пример #2
0
  @Test
  public void testCleanupWithNewToken()
      throws ExecutionException, InterruptedException, UnknownHostException {
    StorageService.instance.getTokenMetadata().clearUnsafe();

    Keyspace keyspace = Keyspace.open(KEYSPACE1);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF2);

    List<Row> rows;

    // insert data and verify we get it back w/ range query
    fillCF(cfs, LOOPS);

    rows = Util.getRangeSlice(cfs);

    assertEquals(LOOPS, rows.size());
    TokenMetadata tmd = StorageService.instance.getTokenMetadata();

    byte[] tk1 = new byte[1], tk2 = new byte[1];
    tk1[0] = 2;
    tk2[0] = 1;
    tmd.updateNormalToken(new BytesToken(tk1), InetAddress.getByName("127.0.0.1"));
    tmd.updateNormalToken(new BytesToken(tk2), InetAddress.getByName("127.0.0.2"));
    CompactionManager.instance.performCleanup(cfs);

    rows = Util.getRangeSlice(cfs);
    assertEquals(0, rows.size());
  }
Пример #3
0
  @Test
  public void selectTest() throws Exception {

    String query;
    Query select;

    query = "SELECT * FROM foo WHERE k=4 AND c>'a' AND c<='z';";
    select = select().all().from("foo").where(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
    assertEquals(query, select.toString());

    query =
        "SELECT a,b,\"C\" FROM foo WHERE a IN (127.0.0.1,127.0.0.3) AND \"C\"='foo' ORDER BY a ASC,b DESC LIMIT 42;";
    select =
        select("a", "b", quote("C"))
            .from("foo")
            .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
            .and(eq(quote("C"), "foo"))
            .orderBy(asc("a"), desc("b"))
            .limit(42);
    assertEquals(query, select.toString());

    query = "SELECT writetime(a),ttl(a) FROM foo;";
    select = select().writeTime("a").ttl("a").from("foo");
    assertEquals(query, select.toString());

    query = "SELECT count(*) FROM foo;";
    select = select().countAll().from("foo");
    assertEquals(query, select.toString());
  }
Пример #4
0
  /**
   * Makes connection to the host server
   *
   * @throws IOException
   */
  private void connectToServer() throws IOException {
    /** Makes new socket and connects it to the server at the specified ID and port */
    client = new Socket(InetAddress.getByName(hostServer), serverPort);

    /** Displays connection information in the update box */
    theView.getUpdateBox().append("Connected with: " + InetAddress.getByName(hostServer) + "\n");
  }
  @Test
  public void oneTx() throws Exception {
    // Check basic tx serialization.
    Coin v1 = COIN;
    Transaction t1 = createFakeTx(params, v1, myAddress);
    t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("1.2.3.4")));
    t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("5.6.7.8")));
    t1.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
    myWallet.receivePending(t1, null);
    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(1, wallet1.getTransactions(true).size());
    assertEquals(v1, wallet1.getBalance(Wallet.BalanceType.ESTIMATED));
    Transaction t1copy = wallet1.getTransaction(t1.getHash());
    assertArrayEquals(t1.bitcoinSerialize(), t1copy.bitcoinSerialize());
    assertEquals(2, t1copy.getConfidence().numBroadcastPeers());
    assertEquals(TransactionConfidence.Source.NETWORK, t1copy.getConfidence().getSource());

    Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(myWallet);
    assertEquals(Protos.Key.Type.ORIGINAL, walletProto.getKey(0).getType());
    assertEquals(0, walletProto.getExtensionCount());
    assertEquals(1, walletProto.getTransactionCount());
    assertEquals(6, walletProto.getKeyCount());

    Protos.Transaction t1p = walletProto.getTransaction(0);
    assertEquals(0, t1p.getBlockHashCount());
    assertArrayEquals(t1.getHash().getBytes(), t1p.getHash().toByteArray());
    assertEquals(Protos.Transaction.Pool.PENDING, t1p.getPool());
    assertFalse(t1p.hasLockTime());
    assertFalse(t1p.getTransactionInput(0).hasSequence());
    assertArrayEquals(
        t1.getInputs().get(0).getOutpoint().getHash().getBytes(),
        t1p.getTransactionInput(0).getTransactionOutPointHash().toByteArray());
    assertEquals(0, t1p.getTransactionInput(0).getTransactionOutPointIndex());
    assertEquals(t1p.getTransactionOutput(0).getValue(), v1.value);
  }
Пример #6
0
  /**
   * Figures out whether the specified address resides within the specified address range.
   *
   * @param range: A range in notation address/netmask, for example 127.0.0.1/255.0.0.0
   * @param address: An address to be tested.
   * @return true if the address is within the range, false otherwise.
   */
  protected boolean isAddressInRange(String range, String address) throws ServletException {

    String network;
    String mask;

    int slashPos = range.indexOf('/');
    if (slashPos == -1) {
      network = range;
      mask = "255.255.255.255";
    } else {
      network = range.substring(0, slashPos);
      mask = range.substring(slashPos + 1);
    }

    try {
      byte[] netBytes = InetAddress.getByName(network).getAddress();
      byte[] maskBytes = InetAddress.getByName(mask).getAddress();
      byte[] addrBytes = InetAddress.getByName(address).getAddress();
      for (int i = 0; i < netBytes.length; i++) {
        if ((netBytes[i] & maskBytes[i]) != (addrBytes[i] & maskBytes[i])) return false;
      }

    } catch (UnknownHostException e) {
      // Should never happen, because we work with raw IP addresses, not
      // with host names.
      throw new ServletException(e.getMessage());
    }

    return true;
  }
Пример #7
0
  private static void send(String s) {
    try {

      String local = "10.0.0.3";
      String remote = "10.0.0.4";
      int localPort = 6679;
      int remotePort = 6614;
      InetAddress lo = InetAddress.getByName(local);
      InetAddress re = InetAddress.getByName(remote);
      ReliableSocket socket = new ReliableSocket(re, remotePort, lo, localPort);

      File img1 = new File(s);
      BufferedImage im1 = ImageIO.read(img1);
      ByteArrayOutputStream baout = new ByteArrayOutputStream();

      ImageIO.write(im1, "jpeg", baout);
      OutputStream out = socket.getOutputStream();
      out.write(baout.toByteArray());
      out.flush();

      // socket.close();
      // socket.close();

    } catch (Exception e) {
      // TODO: handle exception
    }
  }
Пример #8
0
 /* build the trust source set*/
 private static Set getTrustedSourceList() throws SessionException {
   Set result = new HashSet();
   try {
     String rawList = SystemProperties.get(Constants.TRUSTED_SOURCE_LIST);
     if (rawList != null) {
       StringTokenizer stk = new StringTokenizer(rawList, ",");
       while (stk.hasMoreTokens()) {
         result.add(InetAddress.getByName(stk.nextToken()));
       }
     } else {
       // use platform server list as a default fallback
       Vector psl = WebtopNaming.getPlatformServerList();
       if (psl == null) {
         throw new SessionException(SessionBundle.rbName, "emptyTrustedSourceList", null);
       }
       for (Enumeration e = psl.elements(); e.hasMoreElements(); ) {
         try {
           URL url = new URL((String) e.nextElement());
           result.add(InetAddress.getByName(url.getHost()));
         } catch (Exception ex) {
           debug.error("SessionUtils.getTrustedSourceList : " + "Validating Host exception", ex);
         }
       }
     }
   } catch (Exception e) {
     throw new SessionException(e);
   }
   return result;
 }
 private void createSocket() throws IOException {
   if (this.getTheSocket() == null) {
     MulticastSocket socket;
     if (this.isAcknowledge()) {
       if (logger.isDebugEnabled()) {
         logger.debug("Listening for acks on port: " + this.getAckPort());
       }
       if (localAddress == null) {
         socket = new MulticastSocket(this.getAckPort());
       } else {
         InetAddress whichNic = InetAddress.getByName(this.localAddress);
         socket = new MulticastSocket(new InetSocketAddress(whichNic, this.getAckPort()));
       }
       if (this.getSoReceiveBufferSize() > 0) {
         socket.setReceiveBufferSize(this.getSoReceiveBufferSize());
       }
     } else {
       socket = new MulticastSocket();
     }
     if (this.timeToLive >= 0) {
       socket.setTimeToLive(this.timeToLive);
     }
     setSocketAttributes(socket);
     if (localAddress != null) {
       InetAddress whichNic = InetAddress.getByName(this.localAddress);
       NetworkInterface intfce = NetworkInterface.getByInetAddress(whichNic);
       socket.setNetworkInterface(intfce);
     }
     this.setSocket(socket);
   }
 }
Пример #10
0
  /** Publish a request message to the specified multicast group. */
  protected void publishRequest(String message) throws IOException, SocketException {

    groupAddr = InetAddress.getByName(request_group);
    interfaceAddr = InetAddress.getByName(request_interface_address);

    /* is it a multicast address? */
    if (groupAddr.isMulticastAddress()) {

      /* open the socket and join the multicast group */
      udpSocket = new MulticastSocket();
      udpSocket.setNetworkInterface(NetworkInterface.getByInetAddress(interfaceAddr));
      udpSocket.setInterface(interfaceAddr);
      udpSocket.joinGroup(groupAddr);

      /* Send request packet */
      DatagramPacket p =
          new DatagramPacket(message.getBytes(), message.getBytes().length, groupAddr, 7777);

      System.out.println("Sending request: " + new String(p.getData(), 0, p.getLength()));
      udpSocket.send(p);

    } else {
      System.err.println("Invalid multicast address: " + groupAddr.toString());
    }
  }
  @Override
  public int send(String mess) throws Exception, RemoteException, RemoteException {
    if (s == null) {
      try {
        group = InetAddress.getByName(config.getGroup());
        if (config.getHost() != null) {
          InetAddress addr = InetAddress.getByName(config.getHost());
          InetSocketAddress addrs = new InetSocketAddress(addr, config.getMultiport());
          s = new MulticastSocket(addrs);
        } else s = new MulticastSocket(config.getMultiport());

        s.setTimeToLive(config.getTtl());
        s.joinGroup(group);
      } catch (Exception ex) {
        log.error("Unable to use multicast: " + ex);
        s = null;
        return -1;
      }
    }

    byte[] buf;
    buf = mess.getBytes(US_ASCII);
    DatagramPacket data = new DatagramPacket(buf, buf.length, group, config.getMultiport());
    try {
      s.send(data);
    } catch (Exception ex) {
      log.error("Unable to send colllected load information: " + ex);
      s.close();
      s = null;
      return -1;
    }
    return 0;
  }
    /** {@inheritDoc} */
    @Override
    protected Map<String, String> run(Void arg) {
      Map<String, String> res = new HashMap<>();

      try {
        IgniteBiTuple<Collection<String>, Collection<String>> addrs =
            IgniteUtils.resolveLocalAddresses(InetAddress.getByName("0.0.0.0"));

        assert (addrs.get1() != null);
        assert (addrs.get2() != null);

        Iterator<String> ipIt = addrs.get1().iterator();
        Iterator<String> hostIt = addrs.get2().iterator();

        while (ipIt.hasNext() && hostIt.hasNext()) {
          String ip = ipIt.next();

          String hostName = hostIt.next();

          if (hostName == null || hostName.trim().isEmpty()) {
            try {
              if (InetAddress.getByName(ip).isLoopbackAddress()) res.put(ip, "localhost");
            } catch (Exception ignore) {
              // no-op
            }
          } else if (!hostName.equals(ip)) res.put(ip, hostName);
        }
      } catch (Exception e) {
        throw new IgniteException("Failed to resolve host name", e);
      }

      return res;
    }
Пример #13
0
  public static Bundle getSRVRecord(String host) throws IOException {
    InetAddress ip = InetAddress.getByName("8.8.8.8");
    try {
      Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
      Method method = SystemProperties.getMethod("get", new Class[] {String.class});
      ArrayList<String> servers = new ArrayList<String>();
      for (String name :
          new String[] {
            "net.dns1", "net.dns2", "net.dns3", "net.dns4",
          }) {
        String value = (String) method.invoke(null, name);

        if (value != null && !"".equals(value) && !servers.contains(value)) {
          ip = InetAddress.getByName(value);
          servers.add(value);
          Bundle result = queryDNS(host, ip);
          if (!result.containsKey("error") || ("nosrv".equals(result.getString("error")))) {
            return result;
          }
        }
      }
    } catch (Exception e) {
      Log.d("xmppService", "error during system calls");
    }
    ip = InetAddress.getByName("8.8.8.8");
    return queryDNS(host, ip);
  }
Пример #14
0
 // ------------------------------------------------------------
 private void extractPacketData(StorageServer serv, DatagramPacket receivePacket)
     throws IOException {
   try {
     byte[] temp = new byte[4];
     System.arraycopy(receivePacket.getData(), 3, temp, 0, 4);
     serv.IP = InetAddress.getByAddress(temp).getHostAddress();
     // System.out.println("serv.ip: " + serv.IP);
     // serv.IP = receivePacket.getAddress().getHostAddress();
     // System.out.println("serv.ip: " + serv.IP);
     // System.out.println("inetaddress.getbyname() : " +
     // InetAddress.getByName(gwIP))
     /*
      * serv.IP = String.valueOf(receivePacket.getData()[3]) + "." +
      * String.valueOf(receivePacket.getData()[4]) + "." +
      * String.valueOf(receivePacket.getData()[5]) + "." +
      * String.valueOf(receivePacket.getData()[6]);
      */ serv.port = (int) (receivePacket.getData()[7] << 8) + receivePacket.getData()[8];
     System.out.println("Connecting to: " + serv.IP + ":" + serv.port);
     Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port);
     serv.sock = s;
   } catch (IOException e) {
     System.out.println(
         "BIG PROBLEM HERE BECAUSE YOU CANNOT CONNECT " + "BACK!!!!!!!! Trying other address");
     try {
       serv.IP = receivePacket.getAddress().getHostAddress();
       System.out.println("Connecting to: " + serv.IP + ":" + serv.port);
       Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port);
       serv.sock = s;
     } catch (IOException f) {
       System.out.println("cannot connect here aswell\n");
       throw new IOException(f);
     }
   }
 }
Пример #15
0
 /*
  * see if two file systems are the same or not.
  */
 private boolean compareFs(FileSystem srcFs, FileSystem destFs) {
   URI srcUri = srcFs.getUri();
   URI dstUri = destFs.getUri();
   if (srcUri.getScheme() == null) {
     return false;
   }
   if (!srcUri.getScheme().equals(dstUri.getScheme())) {
     return false;
   }
   String srcHost = srcUri.getHost();
   String dstHost = dstUri.getHost();
   if ((srcHost != null) && (dstHost != null)) {
     try {
       srcHost = InetAddress.getByName(srcHost).getCanonicalHostName();
       dstHost = InetAddress.getByName(dstHost).getCanonicalHostName();
     } catch (UnknownHostException ue) {
       return false;
     }
     if (!srcHost.equals(dstHost)) {
       return false;
     }
   } else if (srcHost == null && dstHost != null) {
     return false;
   } else if (srcHost != null && dstHost == null) {
     return false;
   }
   // check for ports
   if (srcUri.getPort() != dstUri.getPort()) {
     return false;
   }
   return true;
 }
Пример #16
0
  /**
   * Generates a new MediaStreamer
   *
   * @param port The port at which to accept incoming media connections
   */
  public MediaStreamer(int port) {
    mediaPort = port;
    cameras = new ArrayList<CameraController>();
    clients = new ArrayList<User>();
    serverSocket = null;
    currentStream = null;
    observer = this;
    lastImageWrite = System.currentTimeMillis();
    nextSeqNum = 0;

    if (ENABLE_TEST_CLIENT) {
      try {
        addUser(new User("MediaTestClient", InetAddress.getByName(TEST_CLIENT_HOSTNAME)));
        log.info(
            "Media Test client established. Serving media stream to: "
                + InetAddress.getByName(TEST_CLIENT_HOSTNAME).getHostAddress()
                + ":"
                + getPort());
      } catch (UnknownHostException e) {
        e.printStackTrace();
      }
    }

    try {
      // Establish the datagram socket.
      serverSocket = new DatagramSocket(mediaPort);
      log.info("MediaServer initialized and waiting at port: " + mediaPort);
    } catch (IOException e) {
      log.error("Socket error in media listen thread, video streaming will not be supported.");
      e.printStackTrace();
      serverSocket = null;
    }
  }
 @Test
 /** Test entire encoding */
 public void testEncoding() throws UnknownHostException {
   String expectedHeader = " 172.17.152.12253200  172.17.152.17 2016D 1";
   String payload = "Hi Mom!";
   String padding = "                       ";
   String checksumStr = " 3352";
   assertEquals("Header length", ReliableTransportMessage.HEADER_LEN, expectedHeader.length());
   assertEquals("padding length", 23, padding.length());
   InetAddress srcIP = InetAddress.getByName("172.17.152.122");
   InetAddress destIP = InetAddress.getByName("172.17.152.17");
   ReliableTransportMessage msg =
       new ReliableTransportMessage(
           srcIP, destIP, 53200, 2016, ReliableTransportMessage.DATA, 1, payload);
   assertEquals("source IP", "/172.17.152.122", msg.getSourceIP().toString());
   assertEquals("dest IP", "/172.17.152.17", msg.getDestIP().toString());
   msg.encode();
   String expectedEncoding = expectedHeader + payload + padding + checksumStr;
   assertEquals("Expected Encoding length", 78, expectedEncoding.length());
   assertEquals(
       "Checksum input length",
       73,
       ReliableTransportMessage.HEADER_LEN + ReliableTransportMessage.PAYLOAD_LEN);
   for (int i = 0; i < 73; i++)
     // check i-th term of checksum
     assertEquals("Checksum term " + i, (int) expectedEncoding.charAt(i), msg.getChecksumTerm(i));
   String encodingStr = new String(msg.getBuffer());
   assertEquals("encoded length", 78, encodingStr.length());
   assertEquals("computed checksum", 3352, msg.getComputedChecksum());
   assertEquals("encoding", expectedEncoding, encodingStr);
 }
  public void main(String[] args) throws UnknownHostException {
    long ipLo = ipToLong(InetAddress.getByName("192.200.0.0"));
    long ipHi = ipToLong(InetAddress.getByName("192.255.0.0"));
    long ipToTest = ipToLong(InetAddress.getByName("192.200.3.0"));

    System.out.println(ipToTest >= ipLo && ipToTest <= ipHi);
  }
Пример #19
0
 // ---------------------------------------------------------
 // decide whether two host names (h1, h2) refer to same IP
 // ---------------------------------------------------------
 public static boolean sameHost(String h1, String h2) {
   try {
     String a1 = InetAddress.getByName(h1).getHostAddress();
     String a2 = InetAddress.getByName(h2).getHostAddress();
     if (a1.equals(a2)) return true;
   } catch (Exception e) {
     System.out.println(e);
   }
   return false;
 }
Пример #20
0
  public boolean verify(String hostname, SSLSession session) {
    if (trustAllServerCerts) {
      return true;
    }

    boolean approve = true;
    X509Certificate peercert = null;
    String cn = null;

    try {
      X509Certificate[] peercerts = (X509Certificate[]) session.getPeerCertificates();
      peercert = peercerts[0];
      String subjectDN = peercert.getSubjectDN().getName();
      cn = new X500Name(subjectDN).getCommonName();
    } catch (Exception ex) {
      debug.error("AMHostnameVerifier:" + ex.toString());
    }

    if (cn == null) return false;

    if (!sslTrustHosts.isEmpty()) {
      if (sslTrustHosts.contains(cn.toLowerCase())) {
        return true;
      }
    }

    if (resolveIPAddress) {
      try {
        approve =
            InetAddress.getByName(cn)
                .getHostAddress()
                .equals(InetAddress.getByName(hostname).getHostAddress());
      } catch (UnknownHostException ex) {
        if (debug.messageEnabled()) {
          debug.message("AMHostnameVerifier:", ex);
        }
        approve = false;
      }
    } else {
      approve = false;
    }

    if (checkSubjectAltName && !approve) {
      try {
        Iterator i = (Iterator) peercert.getSubjectAlternativeNames().iterator();
        for (; !approve && i.hasNext(); ) {
          approve = compareHosts((GeneralName) i.next(), hostname);
        }
      } catch (Exception ex) {
        return false;
      }
    }

    return approve;
  }
Пример #21
0
  public static void main(String[] args) {
    InetAddress addr = null, bind_addr = null;
    int port = 0;
    int ttl = 32;
    long timeout = 2000;
    final String DEFAULT_DIAG_ADDR = "224.0.75.75";
    final int DEFAULT_DIAG_PORT = 7500;
    List<String> query = new ArrayList<String>();
    String match = null;
    boolean weed_out_duplicates = false;

    try {
      for (int i = 0; i < args.length; i++) {
        if ("-addr".equals(args[i])) {
          addr = InetAddress.getByName(args[++i]);
          continue;
        }
        if ("-bind_addr".equals(args[i])) {
          bind_addr = InetAddress.getByName(args[++i]);
          continue;
        }
        if ("-port".equals(args[i])) {
          port = Integer.parseInt(args[++i]);
          continue;
        }
        if ("-ttl".equals(args[i])) {
          ttl = Integer.parseInt(args[++i]);
          continue;
        }
        if ("-timeout".equals(args[i])) {
          timeout = Long.parseLong(args[++i]);
          continue;
        }
        if ("-match".equals(args[i])) {
          match = args[++i];
          continue;
        }
        if ("-weed_out_duplicates".equals(args[i])) {
          weed_out_duplicates = true;
          continue;
        }
        if ("-help".equals(args[i]) || "-h".equals(args[i])) {
          help();
          return;
        }
        query.add(args[i]);
      }
      Probe p = new Probe();
      if (addr == null) addr = InetAddress.getByName(DEFAULT_DIAG_ADDR);
      if (port == 0) port = DEFAULT_DIAG_PORT;
      p.start(addr, bind_addr, port, ttl, timeout, query, match, weed_out_duplicates);
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Пример #22
0
  /**
   * Returns the remote IP address of the client
   *
   * @param servletRequest The HttpServletRequest object which contains the session string.
   * @return InetAddress the client address
   * @exception Exception
   */
  public static InetAddress getClientAddress(HttpServletRequest servletRequest) throws Exception {

    InetAddress remoteClient = InetAddress.getByName(servletRequest.getRemoteAddr());

    if (isTrustedSource(remoteClient)) {
      String proxyHeader = servletRequest.getHeader(httpClientIPHeader);
      if (proxyHeader != null) {
        remoteClient = InetAddress.getByName(proxyHeader);
      }
    }
    return remoteClient;
  }
 /**
  * Test ip encodings
  *
  * @throws UnknownHostException
  */
 public void testIPencoding() throws UnknownHostException {
   InetAddress srcIP = InetAddress.getByName("172.17.152.122");
   InetAddress destIP = InetAddress.getByName("172.17.152.124");
   assertEquals(
       "src ip encoding",
       " 172.17.152.122",
       new String(ReliableTransportMessage.leftPaddedIP(srcIP, 15)));
   assertEquals(
       "dest ip encoding",
       " 172.17.152.124",
       new String(ReliableTransportMessage.leftPaddedIP(destIP, 15)));
 }
 /**
  * Test fields of the constructed object
  *
  * @throws UnknownHostException
  */
 public void testConstructor() throws UnknownHostException {
   InetAddress srcIP = InetAddress.getByName("172.17.152.122");
   InetAddress destIP = InetAddress.getByName("172.17.152.124");
   ReliableTransportMessage msg =
       new ReliableTransportMessage(
           srcIP, destIP, 2200, 2015, ReliableTransportMessage.DATA, 1, "Hi mom!");
   assertEquals("source port: ", 2200, msg.getSrcPort());
   assertEquals("dest port: ", 2015, msg.getDestPort());
   assertEquals("op code", 'D', msg.getOpCode());
   assertEquals("sequence no", 1, msg.getSequenceNo());
   assertEquals("payload", "Hi mom!", msg.getPayload());
 }
Пример #25
0
  public static InetNetwork getFromString(String netspec) throws java.net.UnknownHostException {
    if (netspec.endsWith("*")) netspec = normalizeFromAsterisk(netspec);
    else {
      int iSlash = netspec.indexOf('/');
      if (iSlash == -1) netspec += "/255.255.255.255";
      else if (netspec.indexOf('.', iSlash) == -1) netspec = normalizeFromCIDR(netspec);
    }

    return new InetNetwork(
        InetAddress.getByName(netspec.substring(0, netspec.indexOf('/'))),
        InetAddress.getByName(netspec.substring(netspec.indexOf('/') + 1)));
  }
  /**
   * Retrieves an array of Strings naming the distinct, known to be valid local InetAddress names
   * for this machine. The process is to collect and return the union of the following sets:
   *
   * <ol>
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostName())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostName())
   *   <li>InetAddress.getByName("loopback").getHostAddress()
   *   <li>InetAddress.getByName("loopback").getHostname()
   * </ol>
   *
   * @return the distinct, known to be valid local InetAddress names for this machine
   */
  public static String[] listLocalInetAddressNames() {

    InetAddress addr;
    InetAddress[] addrs;
    HashSet set;

    set = new HashSet();

    try {
      addr = InetAddress.getLocalHost();
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      addr = InetAddress.getByName(null);
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      set.add(InetAddress.getByName("loopback").getHostAddress());
      set.add(InetAddress.getByName("loopback").getHostName());
    } catch (Exception e) {
    }

    return (String[]) set.toArray(new String[set.size()]);
  }
Пример #27
0
  @Test
  public void testCleanupWithIndexes()
      throws IOException, ExecutionException, InterruptedException {
    Keyspace keyspace = Keyspace.open(KEYSPACE1);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF1);

    List<Row> rows;

    // insert data and verify we get it back w/ range query
    fillCF(cfs, LOOPS);
    rows = Util.getRangeSlice(cfs);
    assertEquals(LOOPS, rows.size());

    SecondaryIndex index = cfs.indexManager.getIndexForColumn(COLUMN);
    long start = System.nanoTime();
    while (!index.isIndexBuilt(COLUMN) && System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10))
      Thread.sleep(10);

    // verify we get it back w/ index query too
    IndexExpression expr = new IndexExpression(COLUMN, IndexExpression.Operator.EQ, VALUE);
    List<IndexExpression> clause = Arrays.asList(expr);
    IDiskAtomFilter filter = new IdentityQueryFilter();
    IPartitioner p = StorageService.getPartitioner();
    Range<RowPosition> range = Util.range("", "");
    rows = keyspace.getColumnFamilyStore(CF1).search(range, clause, filter, Integer.MAX_VALUE);
    assertEquals(LOOPS, rows.size());

    // we don't allow cleanup when the local host has no range to avoid wipping up all data when a
    // node has not join the ring.
    // So to make sure cleanup erase everything here, we give the localhost the tiniest possible
    // range.
    TokenMetadata tmd = StorageService.instance.getTokenMetadata();
    byte[] tk1 = new byte[1], tk2 = new byte[1];
    tk1[0] = 2;
    tk2[0] = 1;
    tmd.updateNormalToken(new BytesToken(tk1), InetAddress.getByName("127.0.0.1"));
    tmd.updateNormalToken(new BytesToken(tk2), InetAddress.getByName("127.0.0.2"));

    CompactionManager.instance.performCleanup(cfs, new CounterId.OneShotRenewer());

    // row data should be gone
    rows = Util.getRangeSlice(cfs);
    assertEquals(0, rows.size());

    // not only should it be gone but there should be no data on disk, not even tombstones
    assert cfs.getSSTables().isEmpty();

    // 2ary indexes should result in no results, too (although tombstones won't be gone until
    // compacted)
    rows = cfs.search(range, clause, filter, Integer.MAX_VALUE);
    assertEquals(0, rows.size());
  }
Пример #28
0
  public void testIsMaximum() throws UnknownHostException {
    InetAddress address = InetAddress.getByName("255.255.255.254");
    assertFalse(InetAddresses.isMaximum(address));

    address = InetAddress.getByName("255.255.255.255");
    assertTrue(InetAddresses.isMaximum(address));

    address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe");
    assertFalse(InetAddresses.isMaximum(address));

    address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
    assertTrue(InetAddresses.isMaximum(address));
  }
  static {
    try {
      PROHIBIT_ALL_IPV4 = new AclEntry(InetAddress.getByName("0.0.0.0").getAddress(), 0, false);
      PROHIBIT_ALL_IPV6 = new AclEntry(InetAddress.getByName("::").getAddress(), 0, false);
    } catch (UnknownHostException uke) {

      // Should never reach here, since no name service is needed to
      // look up either address.
      throw new RuntimeException("Unexpected problem in static initializer", uke);
    } catch (AclFormatException afe) {
      throw new RuntimeException("Unexpected problem in static initializer", afe);
    }
  }
	void inetAddress(){
		InetAddress remoteaddress;
		InetAddress localaddress;
		try {
			localaddress = InetAddress.getByName(getLocalIP());	
			remoteaddress = InetAddress.getByName("172.16.35.174");			
			//printReachableIP(remoteaddress, 6379);
			Boolean b=isReachable(localaddress, remoteaddress, 6379, 5000);
			System.out.println(b);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}