Java Code Examples for java.net.InetAddress.getByAddress()

The following are Jave code examples for showing how to use getByAddress() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hashsdn-controller   File: NetUtils.java   Source Code and License Vote up 6 votes
/**
 * Given an IP address and a prefix network mask length, it returns the
 * equivalent subnet prefix IP address Example: for ip = "172.28.30.254" and
 * maskLen = 25 it will return "172.28.30.128"
 *
 * @param ip
 *            the IP address in InetAddress form
 * @param maskLen
 *            the length of the prefix network mask
 * @return the subnet prefix IP address in InetAddress form
 */
public static InetAddress getSubnetPrefix(final InetAddress ip, final int maskLen) {
    int bytes = maskLen / 8;
    int bits = maskLen % 8;
    byte modifiedByte;
    byte[] sn = ip.getAddress();
    if (bits > 0) {
        modifiedByte = (byte) (sn[bytes] >> 8 - bits);
        sn[bytes] = (byte) (modifiedByte << 8 - bits);
        bytes++;
    }
    for (; bytes < sn.length; bytes++) {
        sn[bytes] = (byte) 0;
    }
    try {
        return InetAddress.getByAddress(sn);
    } catch (final UnknownHostException e) {
        return null;
    }
}
 
Example 2
Project: elasticsearch_my   File: TransportAddress.java   Source Code and License Vote up 6 votes
/**
 * Read from a stream and use the {@code hostString} when creating the InetAddress if the input comes from a version prior
 * {@link Version#V_5_0_3_UNRELEASED} as the hostString was not serialized
 */
public TransportAddress(StreamInput in, @Nullable String hostString) throws IOException {
    if (in.getVersion().before(Version.V_6_0_0_alpha1_UNRELEASED)) { // bwc layer for 5.x where we had more than one transport address
        final short i = in.readShort();
        if(i != 1) { // we fail hard to ensure nobody tries to use some custom transport address impl even if that is difficult to add
            throw new AssertionError("illegal transport ID from node of version: " + in.getVersion()  + " got: " + i + " expected: 1");
        }
    }
    final int len = in.readByte();
    final byte[] a = new byte[len]; // 4 bytes (IPv4) or 16 bytes (IPv6)
    in.readFully(a);
    final InetAddress inetAddress;
    if (in.getVersion().onOrAfter(Version.V_5_0_3_UNRELEASED)) {
        String host = in.readString(); // the host string was serialized so we can ignore the passed in version
        inetAddress = InetAddress.getByAddress(host, a);
    } else {
        // prior to this version, we did not serialize the host string so we used the passed in version
        inetAddress = InetAddress.getByAddress(hostString, a);
    }
    int port = in.readInt();
    this.address = new InetSocketAddress(inetAddress, port);
}
 
Example 3
Project: datatree   File: AbstractConverterSet.java   Source Code and License Vote up 5 votes
protected static final InetAddress toInetAddress(byte[] from) {
	try {
		return InetAddress.getByAddress(from);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Unable to convert byte array to InetAddress!");
	}
}
 
Example 4
Project: elasticsearch_my   File: NetworkAddressTests.java   Source Code and License Vote up 5 votes
/**
 * Round trip test code for both IPv4 and IPv6. {@link InetAddress} contains the {@code getByAddress} and
 * {@code getbyName} methods for both IPv4 and IPv6, unless you also specify a {@code scopeid}, which this does not
 * test.
 *
 * @param bytes 4 (32-bit for IPv4) or 16 bytes (128-bit for IPv6)
 * @throws Exception if any error occurs while interacting with the network address
 */
private void roundTrip(byte[] bytes) throws Exception {
    Random random = random();
    for (int i = 0; i < 10000; i++) {
        random.nextBytes(bytes);
        InetAddress expected = InetAddress.getByAddress(bytes);
        String formatted = NetworkAddress.format(expected);
        InetAddress actual = InetAddress.getByName(formatted);
        assertEquals(expected, actual);
    }
}
 
Example 5
Project: rskj   File: InetAddressBlockTest.java   Source Code and License Vote up 5 votes
@Test
public void usingIPV4With9BitsMask() throws UnknownHostException {
    InetAddress address = generateIPAddressV4();
    byte[] bytes = address.getAddress();
    bytes[2] ^= 1;
    InetAddress address2 = InetAddress.getByAddress(bytes);
    bytes[2] ^= 2;
    InetAddress address3 = InetAddress.getByAddress(bytes);

    InetAddressBlock mask = new InetAddressBlock(address, 9);

    Assert.assertTrue(mask.contains(address2));
    Assert.assertFalse(mask.contains(address3));
}
 
Example 6
Project: BUbiNG   File: WorkbenchEntry.java   Source Code and License Vote up 5 votes
@Override
public synchronized String toString() {
	try {
		return "[" + InetAddress.getByAddress(ipAddress) + " (" + visitStates.size() + ")]";
	}
	catch (UnknownHostException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 7
Project: simulacron   File: CqlMapper.java   Source Code and License Vote up 5 votes
@Override
InetAddress decodeInternal(ByteBuffer input) {
  if (input == null || input.remaining() == 0) return null;
  try {
    return InetAddress.getByAddress(Bytes.getArray(input));
  } catch (UnknownHostException e) {
    throw new InvalidTypeException(
        "Invalid bytes for inet value, got " + input.remaining() + " bytes", e);
  }
}
 
Example 8
Project: simulacron   File: CqlMapperTest.java   Source Code and License Vote up 5 votes
@Test
public void shouldHandleInet() throws Exception {
  Codec<InetAddress> inetCodec = mapper.codecFor(primitive(INET));
  assertThat(inetCodec).isSameAs(mapper.inet);

  InetAddress ipv6 =
      InetAddress.getByAddress(
          new byte[] {127, 0, 0, 1, 127, 0, 0, 2, 127, 0, 0, 3, 122, 127, 125, 124});

  InetAddress ipv4 = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});

  // ipv4
  encodeAndDecode(inetCodec, ipv4, "0x7f000001");
  // ipv6
  encodeAndDecode(inetCodec, ipv6, "0x7f0000017f0000027f0000037a7f7d7c");
  encodeAndDecode(inetCodec, null, null);

  encodeObjectAndDecode(inetCodec, ipv4, "0x7f000001", ipv4);
  encodeObjectAndDecode(inetCodec, "127.0.0.1", "0x7f000001", ipv4);
  encodeObjectAndDecode(inetCodec, "notanip.>>>", null, null);
  encodeObjectAndDecode(inetCodec, null, null, null);
  encodeObjectAndDecode(inetCodec, Optional.of(12), null, null);

  try {
    // invalid number of bytes.
    inetCodec.decode(Bytes.fromHexString("0x7f00000102"));
    fail("Shouldn't have been able to decode 5 byte address");
  } catch (InvalidTypeException e) {
    assertThat(e.getCause()).isInstanceOf(UnknownHostException.class);
  }
}
 
Example 9
Project: tomcat7   File: AbstractSender.java   Source Code and License Vote up 5 votes
public void setDestination(Member destination) throws UnknownHostException {
    this.destination = destination;
    this.address = InetAddress.getByAddress(destination.getHost());
    this.port = destination.getPort();
    this.udpPort = destination.getUdpPort();

}
 
Example 10
Project: Nird2   File: LanTcpPlugin.java   Source Code and License Vote up 5 votes
private InetSocketAddress parseSocketAddress(BdfList descriptor)
		throws FormatException {
	byte[] address = descriptor.getRaw(1);
	int port = descriptor.getLong(2).intValue();
	if (port < 1 || port > MAX_16_BIT_UNSIGNED) throw new FormatException();
	try {
		InetAddress addr = InetAddress.getByAddress(address);
		return new InetSocketAddress(addr, port);
	} catch (UnknownHostException e) {
		// Invalid address length
		throw new FormatException();
	}
}
 
Example 11
Project: MKAPP   File: IPUtil.java   Source Code and License Vote up 5 votes
private static InetAddress long2inet(long addr) {
    try {
        byte[] b = new byte[4];
        for (int i = b.length - 1; i >= 0; i--) {
            b[i] = (byte) (addr & 0xFF);
            addr = addr >> 8;
        }
        return InetAddress.getByAddress(b);
    } catch (UnknownHostException ignore) {
        return null;
    }
}
 
Example 12
Project: openhab2-addon-hs110   File: HS110DiscoveryService.java   Source Code and License Vote up 5 votes
public HS110DiscoveryService() throws UnknownHostException {

        super(HS110BindingConstants.SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SECONDS, false);
        byte[] addr = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
        broadcast = InetAddress.getByAddress(addr);
        discoverPacket = new DatagramPacket(discoverbuffer, discoverbuffer.length, broadcast, 9999);

    }
 
Example 13
Project: jdk8u-jdk   File: NoAddresses.java   Source Code and License Vote up 4 votes
public static void main(String[] args)
        throws Exception {

    OneKDC kdc = new OneKDC(null);
    kdc.writeJAASConf();
    KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
            "noaddresses = false",
            "default_keytab_name = " + OneKDC.KTAB);
    Config.refresh();

    Context c = Context.fromJAAS("client");
    Context s = Context.fromJAAS("server");

    c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);

    InetAddress initiator = InetAddress.getLocalHost();
    InetAddress acceptor = InetAddress.getLocalHost();
    switch (args[0]) {
        case "1":
            // no initiator host address available, should be OK
            break;
        case "2":
            // correct initiator host address, still fine
            c.x().setChannelBinding(
                    new ChannelBinding(initiator, acceptor, null));
            s.x().setChannelBinding(
                    new ChannelBinding(initiator, acceptor, null));
            break;
        case "3":
            // incorrect initiator host address, fail
            initiator = InetAddress.getByAddress(new byte[]{1,1,1,1});
            c.x().setChannelBinding(
                    new ChannelBinding(initiator, acceptor, null));
            s.x().setChannelBinding(
                    new ChannelBinding(initiator, acceptor, null));
            break;
    }

    Context.handshake(c, s);
}
 
Example 14
Project: Tenable.io-SDK-for-Java   File: WorkbenchNessusFileParser.java   Source Code and License Vote up 4 votes
@Override
public void gotChild( Asset currentObject, Object child ) {
    if( child instanceof DefaultXmlObject ) {
        DefaultXmlObject c = (DefaultXmlObject)child;
        if( c.getName().toLowerCase() == "tag" ) {
            String tagName = c.getAttributes().get( "name" ).toLowerCase();
            String tagValue = c.getValue();
            try {
                switch( tagName ) {
                    case "bios-uuid":
                        currentObject.setBiosUuid( UUID.fromString( tagValue ) );
                        break;
                    case "host-fqdn":
                        currentObject.setHostFqdn( tagValue );
                        break;
                    case "hostname":
                        currentObject.setHostName( tagValue );
                        break;
                    case "host-ip":
                        String[] ipChunks = tagValue.split( "\\." );
                        if( ipChunks.length == 4 ) {
                            byte[] hostIp = new byte[4];
                            for( int i = 0; i < 4; i++ )
                                hostIp[i] = (byte)Integer.parseInt( ipChunks[i] );

                            InetAddress address = InetAddress.getByAddress( tagValue, hostIp );
                            if( address instanceof Inet4Address )
                                currentObject.setHostIpV4( (Inet4Address)address );
                        }
                        break;
                    case "host-uuid":
                        currentObject.setId( UUID.fromString( tagValue ) );
                        break;
                    case "host_start":
                        currentObject.setLastHostScanStart( DateHelper.parseIso8601Date( tagValue ) );
                        break;
                    case "host_end":
                        currentObject.setLastHostScanEnd( DateHelper.parseIso8601Date( tagValue ) );
                        break;
                    case "lastauthenticatedresults":
                        currentObject.setLastAuthenticatedResult( DateHelper.parseIso8601Date( tagValue ) );
                        break;
                    case "local-checks-proto":
                        currentObject.setLastAuthenticatedScanProto( tagValue );
                        break;
                    case "mac-macaddress":
                        String[] macs = tagValue.split( "\n" );
                        for( String mac : macs ) {
                            mac = mac.trim();
                            if( mac.length() > 0 ) // the last mac is typically a sequence of spaces
                                currentObject.addMacAddress( MacAddressHelper.parse( mac ) );
                        }
                        break;
                    case "mcafee-epo-guid":
                        currentObject.setMcAfeeApoGuid( UUID.fromString( tagValue ) );
                        break;
                    case "netbios-name":
                        currentObject.setNetbiosName( tagValue );
                        break;
                    case "operating-system":
                        currentObject.setOperatingSystem( tagValue );
                        break;
                    case "system-type":
                        currentObject.setSystemType( tagValue );
                        break;
                }
            } catch( Exception e ) {
                logger.warn( String.format( "Exception when parsing Host Properties tag \'%s\' with value \'%s\'", tagName, tagValue ), e );
            }
        }
    }
}
 
Example 15
Project: athena   File: AthenaProxy.java   Source Code and License Vote up 4 votes
public void installBlockRule(TargetAthenaValue ipSrc, TargetAthenaValue ipDst, String deviceUri) {

            ///////////////////////////////Debug///////////////////////////////////////
            Integer sip = (Integer) ipSrc.getTargetAthenaValue();
            Integer dip = (Integer) ipDst.getTargetAthenaValue();
            byte[] sbytes = BigInteger.valueOf(sip).toByteArray();
            byte[] dbytes = BigInteger.valueOf(sip).toByteArray();
            InetAddress saddress = null;
            InetAddress daddress = null;
            try {
                saddress = InetAddress.getByAddress(sbytes);
                daddress = InetAddress.getByAddress(dbytes);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            DeviceId deviceId = DeviceId.deviceId(deviceUri);

            TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();

            Ip4Prefix matchIp4SrcPrefix =
                    Ip4Prefix.valueOf(((Integer) ipSrc.getTargetAthenaValue()).intValue(),
                            Ip4Prefix.MAX_MASK_LENGTH);
            Ip4Prefix matchIp4DstPrefix =
                    Ip4Prefix.valueOf(((Integer) ipDst.getTargetAthenaValue()).intValue(),
                            Ip4Prefix.MAX_MASK_LENGTH);
            selectorBuilder.matchEthType(Ethernet.TYPE_IPV4)
                    .matchIPSrc(matchIp4SrcPrefix)
                    .matchIPDst(matchIp4DstPrefix);

            TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                    .build();

            ForwardingObjective forwardingObjective = DefaultForwardingObjective.builder()
                    .withSelector(selectorBuilder.build())
                    .withTreatment(treatment)
                    .withPriority(flowPriority)
                    .withFlag(ForwardingObjective.Flag.VERSATILE)
                    .fromApp(appId)
                    .makeTemporary(flowTimeout)
                    .add();

            log.info("Block!!" + saddress.getHostAddress() + daddress.getHostAddress() + deviceUri);
            flowObjectiveService.forward(deviceId,
                    forwardingObjective);
        }
 
Example 16
Project: raven   File: HttpConnectionAdaptor.java   Source Code and License Vote up 4 votes
private CloseableHttpClient createHttpClient() throws NSPException {
	try {
		initSocketFactory();

		DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
			public InetAddress[] resolve(String host)
					throws UnknownHostException {
				if (host.equalsIgnoreCase("localhost")) {
					return new InetAddress[] { InetAddress
							.getByAddress(new byte[] { 127, 0, 0, 1 }) };
				}

				return super.resolve(host);
			}
		};
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
				this.socketFactoryRegistry, dnsResolver);

		SocketConfig socketConfig = SocketConfig.custom()
				.setTcpNoDelay(true).setSoKeepAlive(true).setSoLinger(0)
				.setSoReuseAddress(true).build();

		connManager.setDefaultSocketConfig(socketConfig);

		ConnectionConfig connectionConfig = ConnectionConfig.custom()
				.setCharset(Consts.UTF_8).build();
		connManager.setDefaultConnectionConfig(connectionConfig);
		connManager.setConnectionConfig(new HttpHost("localhost", 80),
				ConnectionConfig.DEFAULT);

		connManager.setMaxTotal(this.mMaxConnections);

		if ((this.mMaxConnections <= this.mConnectionsPerRoute)
				&& (this.mMaxConnections > 0)) {
			this.mConnectionsPerRoute = this.mMaxConnections;
		}

		connManager.setDefaultMaxPerRoute(this.mConnectionsPerRoute);

		connManager.setMaxPerRoute(new HttpRoute(new HttpHost("localhost",
				80)), 100);

		CloseableHttpClient httpclient = HttpClients
				.custom()
				.setConnectionManager(connManager)
				.setDefaultRequestConfig(
						RequestConfig.copy(defaultRequestConfig).build())
				.build();

		return ((CloseableHttpClient) new WeakReference(httpclient).get());
	} catch (Exception e) {
		throw new NSPException(2, "Service unavailable.", e);
	}
}
 
Example 17
Project: openNaEF   File: MplsNmsNodeInfoFactory.java   Source Code and License Vote up 4 votes
@Override
public NodeInfo createNodeInfo(NodeDto node) throws IOException {
    Logger log = LoggerFactory.getLogger(MplsNmsNodeInfoFactory.class);
    if (node == null) {
        throw new IllegalArgumentException();
    }

    try {
        String ipAddress = NodeRenderer.getManagementIpAddress(node);
        String snmpRO = NodeRenderer.getSnmpCommunity(node);
        String snmpMethod = NodeRenderer.getSnmpMode(node);
        String userName = NodeRenderer.getConsoleLoginUserName(node);
        String userPass = NodeRenderer.getConsoleLoginPassword(node);
        String adminName = NodeRenderer.getPrivilegedUserName(node);
        String adminPass = NodeRenderer.getPrivilegedLoginPassword(node);

        if (snmpRO == null) {
            snmpRO = MplsNmsDiffConfiguration.getInstance().getDefaultSnmpCommunityString();
            log.info("using default snmp-community: " + snmpRO + " (" + node.getName() + ")");
        } else {
            log.info("using snmp-community: " + snmpRO + " (" + node.getName() + ")");
        }
        if (snmpMethod == null) {
            snmpMethod = MplsNmsDiffConfiguration.getInstance().getDefaultSnmpMethod();
            log.info("using default snmp-method: " + snmpMethod + " (" + node.getName() + ")");
        } else {
            log.info("using snmp-method: " + snmpMethod + " (" + node.getName() + ")");
        }

        NodeInfo nodeinfo = new NodeInfo(node.getName());
        if (ipAddress != null) {
            InetAddress inetAddress = InetAddress.getByAddress(
                    VossMiscUtility.getByteFormIpAddress(ipAddress));
            nodeinfo.addIpAddress(inetAddress);
        }
        nodeinfo.setCommunityStringRO(snmpRO);
        nodeinfo.setUserAccount(userName);
        nodeinfo.setUserPassword(userPass);
        nodeinfo.setAdminAccount(adminName);
        nodeinfo.setAdminPassword(adminPass);
        Protocol p = Protocol.getByCaption(snmpMethod);
        ProtocolPort pp = new ProtocolPort(p);
        nodeinfo.addSupportedProtocol(pp);
        nodeinfo.addSupportedProtocol(ProtocolPort.TELNET);
        return nodeinfo;
    } catch (UnknownHostException e) {
        log.warn("failed to create nodeinfo: " + node.getName(), e);
        return null;
    }
}
 
Example 18
Project: googles-monorepo-demo   File: InetAddresses.java   Source Code and License Vote up 3 votes
/**
 * Convert a byte array into an InetAddress.
 *
 * {@link InetAddress#getByAddress} is documented as throwing a checked exception
 * "if IP address is of illegal length." We replace it with an unchecked exception, for use by
 * callers who already know that addr is an array of length 4 or 16.
 *
 * @param addr the raw 4-byte or 16-byte IP address in big-endian order
 * @return an InetAddress object created from the raw IP address
 */
private static InetAddress bytesToInetAddress(byte[] addr) {
  try {
    return InetAddress.getByAddress(addr);
  } catch (UnknownHostException e) {
    throw new AssertionError(e);
  }
}
 
Example 19
Project: hekate   File: MulticastSeedNodeProvider.java   Source Code and License Vote up 3 votes
private InetSocketAddress decodeAddress(ByteBuf buf) throws UnknownHostException {
    byte[] addrBytes = new byte[buf.readByte()];

    buf.readBytes(addrBytes);

    int port = buf.readInt();

    return new InetSocketAddress(InetAddress.getByAddress(addrBytes), port);
}
 
Example 20
Project: BiglyBT   File: NetworkAdminASNImpl.java   Source Code and License Vote up 3 votes
protected InetAddress
getCIDREndAddress()

	throws NetworkAdminException
{

	int	pos = bgp_prefix.indexOf('/');

	try{
		InetAddress	start = InetAddress.getByName( bgp_prefix.substring(0,pos));

		int	cidr_mask = Integer.parseInt( bgp_prefix.substring( pos+1 ));

		int	rev_mask = 0;

		for (int i=0;i<32-cidr_mask;i++){


			rev_mask = ( rev_mask << 1 ) | 1;
		}

		byte[]	bytes = start.getAddress();

		bytes[0] |= (rev_mask>>24)&0xff;
		bytes[1] |= (rev_mask>>16)&0xff;
		bytes[2] |= (rev_mask>>8)&0xff;
		bytes[3] |= (rev_mask)&0xff;

		return( InetAddress.getByAddress( bytes ));

	}catch( Throwable e ){

		throw( new NetworkAdminException( "Parse failure for '" + bgp_prefix + "'", e ));
	}
}