@Test
  public void testSocketBind() throws Exception {
    final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
    final int localPort = 8888;
    final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
    final int remotePort = 80;
    final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort);
    final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort);
    Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress);
    Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress);
    Mockito.when(socket.getLocalAddress()).thenReturn(localAddress);
    Mockito.when(socket.getLocalPort()).thenReturn(localPort);
    Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress);
    Mockito.when(socket.getPort()).thenReturn(remotePort);
    conn.bind(socket);

    Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString());
    Assert.assertTrue(conn.isOpen());
    Assert.assertEquals(8888, conn.getLocalPort());
    Assert.assertEquals(80, conn.getRemotePort());
    Assert.assertEquals(
        InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), conn.getLocalAddress());
    Assert.assertEquals(
        InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), conn.getRemoteAddress());
  }
Example #2
0
  public static InetAddress getByAddress(String addr) {
    if (addr.contains("/")) {
      String[] arr = addr.split("/");
      addr = arr[arr.length - 1];
    }

    try {

      byte[] bytes;
      bytes = toByteArray(addr, IPv4);
      if (bytes != null) {

        return InetAddress.getByAddress(addr, bytes);
      }
      bytes = toByteArray(addr, IPv6);
      if (bytes != null) {
        return InetAddress.getByAddress(addr, bytes);
      }
      throw new UnknownHostException("Invalid address: " + addr);

    } catch (UnknownHostException ex) {
      Logger.getLogger(NamedImpl.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    }
  }
Example #3
0
  private void calculate() throws UnknownHostException {

    ByteBuffer maskBuffer;
    int targetSize;
    if (inetAddress.getAddress().length == 4) {
      maskBuffer = ByteBuffer.allocate(4).putInt(-1);
      targetSize = 4;
    } else {
      maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
      targetSize = 16;
    }

    BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);

    ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    BigInteger ipVal = new BigInteger(1, buffer.array());

    BigInteger startIp = ipVal.and(mask);
    BigInteger endIp = startIp.add(mask.not());

    byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
    byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);

    this.startAddress = InetAddress.getByAddress(startIpArr);
    this.endAddress = InetAddress.getByAddress(endIpArr);
  }
  @Override
  protected Packet getWholePacket() throws UnknownHostException {
    IcmpV4CommonPacket.Builder icmpV4b = new IcmpV4CommonPacket.Builder();
    icmpV4b
        .type(IcmpV4Type.PARAMETER_PROBLEM)
        .code(IcmpV4Code.POINTER_INDICATES_ERROR)
        .payloadBuilder(new SimpleBuilder(packet))
        .correctChecksumAtBuild(true);

    IpV4Packet.Builder ipv4b = new IpV4Packet.Builder();
    ipv4b
        .version(IpVersion.IPV4)
        .tos(IpV4Rfc1349Tos.newInstance((byte) 0))
        .identification((short) 100)
        .ttl((byte) 100)
        .protocol(IpNumber.ICMPV4)
        .srcAddr(
            (Inet4Address)
                InetAddress.getByAddress(new byte[] {(byte) 192, (byte) 0, (byte) 2, (byte) 1}))
        .dstAddr(
            (Inet4Address)
                InetAddress.getByAddress(new byte[] {(byte) 192, (byte) 0, (byte) 2, (byte) 2}))
        .payloadBuilder(icmpV4b)
        .correctChecksumAtBuild(true)
        .correctLengthAtBuild(true);

    EthernetPacket.Builder eb = new EthernetPacket.Builder();
    eb.dstAddr(MacAddress.getByName("fe:00:00:00:00:02"))
        .srcAddr(MacAddress.getByName("fe:00:00:00:00:01"))
        .type(EtherType.IPV4)
        .payloadBuilder(ipv4b)
        .paddingAtBuild(true);
    return eb.build();
  }
 public void testGetAcceptorAddress_0() throws Exception {
   byte data[] = {0, 10, 20, 40, 50};
   InetAddress addr1 = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
   InetAddress addr2 = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
   ChannelBinding cb = new ChannelBinding(addr1, addr2, data);
   assertEquals(InetAddress.getByAddress(new byte[] {127, 0, 0, 2}), cb.getAcceptorAddress());
 }
 public void testGetApplicationData_0() throws Exception {
   byte data[] = {0, 10, 20, 40, 50};
   InetAddress addr1 = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
   InetAddress addr2 = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
   ChannelBinding cb = new ChannelBinding(addr1, addr2, data);
   assertTrue(Arrays.equals(new byte[] {0, 10, 20, 40, 50}, cb.getApplicationData()));
 }
 public void testEquals_Negative_3() throws Exception {
   byte data[] = {0, 10, 20, 30};
   InetAddress addr1 = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
   InetAddress addr2 = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
   ChannelBinding cb = new ChannelBinding(addr1, addr2, data);
   assertTrue(!(new ChannelBinding(addr1, addr2, new byte[] {0, 10, 20})).equals(cb));
 }
 /** Returns the address */
 public InetAddress getAddress() {
   try {
     if (name == null) return InetAddress.getByAddress(address);
     else return InetAddress.getByAddress(name.toString(), address);
   } catch (UnknownHostException e) {
     return null;
   }
 }
Example #9
0
  @Before
  public void setup() throws Exception {
    BriefLogFormatter.init();
    tx1 = TestUtils.createFakeTx(params, Utils.toNanoCoins(1, 0), new ECKey().toAddress(params));
    tx2 = new Transaction(params, tx1.bitcoinSerialize());

    address1 = new PeerAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}));
    address2 = new PeerAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 2}));
    address3 = new PeerAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 3}));
  }
Example #10
0
  @Test
  public void sidnIPNetmaskASN() throws UnknownHostException {
    InetAddress addr = InetAddress.getByAddress(IPUtil.ipv4tobytes("94.198.159"));
    String country = geo.lookupCountry(addr);
    Assert.assertEquals("NL", country);

    addr = InetAddress.getByAddress(IPUtil.ipv6tobytes("2a00:d78::147:94:198:152"));
    country = geo.lookupCountry(addr);
    Assert.assertEquals("NL", country);
  }
  public void testEquals_2_0() throws Exception {
    byte data[] = null;
    InetAddress addr1 = null;
    InetAddress addr2 = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
    ChannelBinding cb = new ChannelBinding(addr1, addr2, data);

    assertTrue(
        (new ChannelBinding(null, InetAddress.getByAddress(new byte[] {127, 0, 0, 2}), null))
            .equals(cb));
  }
 public NetworkInterfaceAddress(
     byte[] address, byte[] subnet, byte[] broadcast, byte[] destination) {
   try {
     if (address != null) this.address = InetAddress.getByAddress(address);
     if (subnet != null) this.subnet = InetAddress.getByAddress(subnet);
     if (broadcast != null) this.broadcast = InetAddress.getByAddress(broadcast);
     if (destination != null) this.destination = InetAddress.getByAddress(destination);
   } catch (UnknownHostException e) {
   }
 }
  private static Instance getInstance(byte[] ipAddress, int dataPort, String hostname, int slots)
      throws Exception {
    HardwareDescription hardwareDescription =
        new HardwareDescription(4, 2L * 1024 * 1024 * 1024, 1024 * 1024 * 1024, 512 * 1024 * 1024);

    InstanceConnectionInfo connection = mock(InstanceConnectionInfo.class);
    when(connection.address()).thenReturn(InetAddress.getByAddress(ipAddress));
    when(connection.dataPort()).thenReturn(dataPort);
    when(connection.getInetAdress()).thenReturn(InetAddress.getByAddress(ipAddress).toString());
    when(connection.getHostname()).thenReturn(hostname);
    when(connection.getFQDNHostname()).thenReturn(hostname);

    return new Instance(taskManager, connection, new InstanceID(), hardwareDescription, slots);
  }
Example #14
0
  public static InetAddress getRubyInetAddress(ByteList address) throws UnknownHostException {
    // switched to String because the ByteLists were not comparing properly in 1.9 mode (encoding?
    // FIXME: Need to properly decode this string (see Helpers.decodeByteList)
    String addressString = Helpers.byteListToString(address);

    if (addressString.equals(BROADCAST)) {
      return InetAddress.getByAddress(INADDR_BROADCAST);

    } else if (addressString.equals(ANY)) {
      return InetAddress.getByAddress(INADDR_ANY);

    } else {
      return InetAddress.getByName(addressString);
    }
  }
Example #15
0
 public MockConnectionInfo(IPv4Addr addr, int port) throws UnknownHostException {
   super(null, ConnectionType.ACTIVE);
   this.remoteAddr = InetAddress.getByAddress(addr.toBytes());
   this.remotePort = port;
   this.localAddr = InetAddress.getLocalHost();
   this.localPort = new Random().nextInt(1000) + 51000;
 }
Example #16
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);
     }
   }
 }
Example #17
0
 /**
  * Returns a textual representation of this device DIB.
  *
  * <p>
  *
  * @return a string representation of the object
  */
 public String toString() {
   InetAddress mc = null;
   try {
     mc = InetAddress.getByAddress(getMulticastAddress());
   } catch (final UnknownHostException ignore) {
   }
   return "device "
       + address
       + " \""
       + name
       + "\" KNX medium "
       + getKNXMediumString()
       + ", installation "
       + getInstallation()
       + " project "
       + getProject()
       + " (project-installation-ID "
       + projectInstallID
       + ")"
       + ", routing multicast address "
       + mc
       + ", MAC address "
       + getMACAddressString()
       + ", S/N 0x"
       + getSerialNumberString();
 }
  /** Bind using a SOCKS server. */
  private void socksBind() throws IOException {
    try {
      netImpl.connect(fd, trafficClass, socksGetServerAddress(), socksGetServerPort());
    } catch (Exception e) {
      throw new IOException(Msg.getString("K003f", e)); // $NON-NLS-1$
    }

    // There must be a connection to an application host for the bind to
    // work.
    if (lastConnectedAddress == null) {
      throw new SocketException(Msg.getString("K0040")); // $NON-NLS-1$
    }

    // Use the last connected address and port in the bind request.
    socksSendRequest(Socks4Message.COMMAND_BIND, lastConnectedAddress, lastConnectedPort);
    Socks4Message reply = socksReadReply();

    if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
      throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
    }

    // A peculiarity of socks 4 - if the address returned is 0, use the
    // original socks server address.
    if (reply.getIP() == 0) {
      address = socksGetServerAddress();
    } else {
      // IPv6 support not yet required as
      // currently the Socks4Message.getIP() only returns int,
      // so only works with IPv4 4byte addresses
      byte[] replyBytes = new byte[4];
      NetUtil.intToBytes(reply.getIP(), replyBytes, 0);
      address = InetAddress.getByAddress(replyBytes);
    }
    localport = reply.getPort();
  }
  @Override
  public void decodeBER(BERInputStream inputStream) throws java.io.IOException {
    BER.MutableByte type = new BER.MutableByte();
    byte[] value = BER.decodeString(inputStream, type);
    if (type.getValue() != BER.IPADDRESS) {
      throw new IOException("Wrong type encountered when decoding Counter: " + type.getValue());
    }
    if (value.length != 4) {
      if ((value.length == 8)
          && Boolean.getBoolean("org.opennms.snmp.workarounds.allow64BitIpAddress")) {
        byte[] tempValue = {0, 0, 0, 0};
        for (int i = 0; i < 4; i++) {
          tempValue[i] = value[i];
        }
        value = tempValue;
        if (log().isDebugEnabled()) {
          log()
              .debug(
                  "Working around misencoded IpAddress (8 bytes, truncating to 4); likely dealing with a buggy Net-SNMP agent");
        }
      } else {
        throw new IOException("IpAddress encoding error, wrong length: " + value.length);
      }
    }

    this.setInetAddress(InetAddress.getByAddress(value));
  }
 static {
   try {
     DEFAULT_BIND_ADDRESS = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
   } catch (UnknownHostException e) {
     throw new RuntimeException(e);
   }
 }
Example #21
0
 private static InetAddress bytesToInetAddress(byte[] paramArrayOfByte) {
   try {
     return InetAddress.getByAddress(paramArrayOfByte);
   } catch (UnknownHostException localUnknownHostException) {
     throw new AssertionError(localUnknownHostException);
   }
 }
  private static void parseTCPMsg(byte[] msg) throws UnknownHostException {
    switch (msg[0]) {
      case 0x00:
        if (msg[1] == 0x01) System.out.println("Server: OPEN");
        else System.out.println("Server: CLOSED");
        break;
      case 0x01:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else {
          ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(msg, 1, msg.length));
          userId = new UUID(buffer.getLong(), buffer.getLong());
          groupIp =
              InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(buffer.getInt()).array());

          // connect to the group and start receiving
          udpSocket.connect(groupIp.getHostAddress());
          udpSocket.startReceive(new UDPHandler());

          System.out.printf(
              "User ID: %s\nGroup IP: %s\nPort: %d\n",
              userId.toString(), groupIp.getHostAddress(), buffer.getInt());
        }
        break;
      case 0x02:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else System.out.println("Successfully deregestered");
      default:
        System.out.println("[ERR] Inavlid msg");
    }
  }
 /**
  * Returns a SubscriberID object from a byte array
  *
  * @param data - the data to parse
  * @return - the object or null if cannot be parsed TODO - make me more robust as
  *     RuntimeExceptions can be thrown here.
  */
 public static SubscriberID parse(final byte[] data) {
   try {
     return new SubscriberID(InetAddress.getByAddress(data));
   } catch (UnknownHostException e) {
     return null;
   }
 }
Example #24
0
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
   //		public String version;
   int len = in.readInt();
   byte[] bytes = new byte[len];
   in.read(bytes);
   version = new String(bytes);
   //		public Group group;
   group = new Group();
   group.readExternal(in);
   //		public ViewID id;
   id = new ViewID();
   id.readExternal(in);
   //		public ViewID[] previous;
   len = in.readInt();
   previous = new ViewID[len];
   for (int i = 0; i < len; i++) {
     previous[i] = new ViewID();
     previous[i].readExternal(in);
   }
   //		public Endpt[] view;
   len = in.readInt();
   view = new Endpt[len];
   for (int i = 0; i < len; i++) view[i].readExternal(in);
   //		public InetWithPort[] addresses;
   len = in.readInt();
   int addrLen = 0;
   addresses = new InetSocketAddress[len];
   for (int i = 0; i < len; i++) {
     addrLen = in.readInt();
     bytes = new byte[addrLen];
     in.read(bytes);
     addresses[i] = new InetSocketAddress(InetAddress.getByAddress(bytes), in.readInt());
   }
 }
 public InetAddress toInetAddress() {
   try {
     return InetAddress.getByAddress(toByteArray());
   } catch (UnknownHostException e) {
     throw new IllegalStateException("Unreachable section!");
   }
 }
 private InetAddress getMulticastAddress(short universe) throws UnknownHostException {
   ByteBuffer bytes = ByteBuffer.allocate(4);
   bytes.put(MULTICAST_BYTE_1);
   bytes.put(MULTICAST_BYTE_2);
   bytes.putShort(universe);
   return InetAddress.getByAddress(bytes.array());
 }
  public static String sendMessage(String message, String port) throws Exception {
    Socket socket = null;
    String rcvdMessage = null;
    try {
      socket =
          new Socket(InetAddress.getByAddress(new byte[] {10, 0, 2, 2}), Integer.parseInt(port));
      socket.setSoTimeout(1500);
      ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
      out.writeObject(message);
      out.flush();
      // Log.v(TAG, "sendMessage:: " + message + " sent to " + port);
      // Receive ACK of insert
      ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
      rcvdMessage = (String) in.readObject();
      // Log.v(TAG, "Received message "+rcvdMessage);
      out.close();
      in.close();
    } catch (UnknownHostException e) {
      Log.e(TAG, "ClientTask UnknownHostException");
      throw e;
    } catch (SocketTimeoutException e) {
      Log.e(TAG, "SocketTimeoutException has occured");
      throw e;
    } catch (IOException e) {
      Log.e(TAG, "ClientTask socket IOException");
      throw e;
    } catch (Exception e) {
      Log.e(TAG, "Some other exception occured in unicast");
      e.printStackTrace();
      ;
    } finally {

    }
    return rcvdMessage;
  }
 /**
  * Gets the next available address in this address pool.
  *
  * @return the next available address
  */
 public InetAddress getNextAvailableAddress() {
   if (freeList != null) {
     BigInteger next = freeList.getNextFree();
     if (next != null) {
       try {
         InetAddress ip = InetAddress.getByAddress(next.toByteArray());
         int pingCheckTimeout =
             DhcpServerPolicies.globalPolicyAsInt(Property.V4_PINGCHECK_TIMEOUT);
         if (pingCheckTimeout > 0) {
           try {
             if (ip.isReachable(pingCheckTimeout)) {
               log.warn("Next free address answered ping check: " + ip.getHostAddress());
               setUsed(ip);
               return getNextAvailableAddress(); // try again
             }
           } catch (IOException ex) {
             log.error("Failed to perform v4 ping check: " + ex);
           }
         }
         return ip;
       } catch (UnknownHostException ex) {
         log.error("Unable to build IPv4 address from next free: " + ex);
       }
     }
   }
   return null;
 }
 private Optional<InetAddress> getRemoteAddress(byte[] addressAsBytes) {
   try {
     return Optional.fromNullable(InetAddress.getByAddress(addressAsBytes));
   } catch (Exception ex) {
     return Optional.absent();
   }
 }
Example #30
0
 /** Returns the Internet address */
 public InetAddress getAddress() {
   try {
     return InetAddress.getByAddress(toArray(addr));
   } catch (UnknownHostException e) {
     return null;
   }
 }