Example usage for java.net InetAddress getByAddress

List of usage examples for java.net InetAddress getByAddress

Introduction

In this page you can find the example usage for java.net InetAddress getByAddress.

Prototype

public static InetAddress getByAddress(byte[] addr) throws UnknownHostException 

Source Link

Document

Returns an InetAddress object given the raw IP address .

Usage

From source file:org.rhq.plugins.platform.content.yum.YumServer.java

/**
 * Get the bind IP address./*from   w w  w .  j  a  v  a 2  s  .com*/
 *
 * @return An address to bind.
 *
 * @throws UnknownHostException
 */
private InetAddress bindAddress() throws UnknownHostException {
    byte[] host = { 127, 0, 0, 1 };
    return InetAddress.getByAddress(host);
}

From source file:net.mm2d.dmsexplorer.ServerListActivity.java

private InetAddress getWifiInetAddress() {
    final WifiInfo wi = ((WifiManager) getSystemService(WIFI_SERVICE)).getConnectionInfo();
    if (wi == null) {
        return null;
    }/*from  w w w  . java 2s  .c  o  m*/
    try {
        return InetAddress.getByAddress(intToByteArray(wi.getIpAddress()));
    } catch (final UnknownHostException ignored) {
    }
    return null;
}

From source file:org.cc86.MMC.client.Main.java

public static void serverDiscoveryHack(String[] args) {
    try {/*from  ww  w .ja va  2s . c  om*/

        final boolean[] foundSomething = { false };
        List<InetAddress> addrList = new ArrayList<InetAddress>();
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            try {
                NetworkInterface ifc = (NetworkInterface) interfaces.nextElement();

                if (ifc.isUp()) {
                    Enumeration addresses = ifc.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = (InetAddress) addresses.nextElement();
                        if (addr instanceof Inet6Address) {
                            continue;
                        }
                        byte[] addrraw = addr.getAddress();
                        for (int i = 1; i < 254; i++) {
                            try {
                                final InetAddress calculated = InetAddress.getByAddress(
                                        new byte[] { addrraw[0], addrraw[1], addrraw[2], (byte) i });
                                new Thread(() -> {
                                    //c=new TCPConnection(calculated.getHostAddress(), 0xCC86);
                                    try {
                                        Socket client = new Socket();
                                        client.connect(
                                                new InetSocketAddress(calculated.getHostAddress(), 0xcc87),
                                                2000);
                                        synchronized (foundSomething) {
                                            if (!foundSomething[0]) {
                                                foundSomething[0] = true;
                                                ArrayList<String> lst = new ArrayList(Arrays.asList(args));
                                                lst.add("-i");
                                                lst.add(calculated.getHostAddress());
                                                main(lst.toArray(args));
                                            }
                                        }
                                    } catch (IOException ex) {
                                        //System.out.println(ex.m);
                                        l.trace("Dead host");
                                        //System.exit(0);
                                    }
                                }).start();
                            } catch (UnknownHostException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
        }

    } catch (SocketException ex) {
        ex.printStackTrace();
    }
}

From source file:it.infn.ct.jsaga.adaptor.jocci.job.jOCCIJobControlAdaptor.java

public boolean testIpAddress(byte[] testAddress) {
    Inet4Address inet4Address;//  ww w . ja  v a 2 s .com
    boolean result = false;

    try {
        inet4Address = (Inet4Address) InetAddress.getByAddress(testAddress);
        result = inet4Address.isSiteLocalAddress();
    } catch (UnknownHostException ex) {
        java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public void init() {

    available = new Semaphore(maxParallel(), true);

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override// ww  w .  j  a  va2 s . c  o  m
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return new InetAddress[] { nameResolver().resolve(host) };
            }
        }
    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount)
            .setMaxLineLength(maxLineLength).build();

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(maxPersistentConnections());
    connManager.setDefaultMaxPerRoute(maxPersistentConnections());

    // TODO
    // Use custom credentials provider if necessary.
    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();

    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects())
            .setSocketTimeout(socketTimeout()).setConnectTimeout(connectTimeout())
            .setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build();

    // Create an HttpClient with the given custom dependencies and
    // configuration.
    client = HttpClients.custom().setConnectionManager(connManager)
            // .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:ugr.cristian.serverVideoApp.AudioRouting.java

static private InetAddress intToInetAddress(int i) {
    byte b[] = new byte[] { (byte) ((i >> 24) & 0xff), (byte) ((i >> 16) & 0xff), (byte) ((i >> 8) & 0xff),
            (byte) (i & 0xff) };
    InetAddress addr;// w  ww  . jav a  2s. com
    try {
        addr = InetAddress.getByAddress(b);
    } catch (UnknownHostException e) {
        return null;
    }

    return addr;
}

From source file:com.alliander.osgp.adapter.protocol.oslp.elster.infra.networking.OslpChannelHandlerServer.java

private Oslp.Message handleRegisterDeviceRequest(final byte[] deviceUid, final byte[] sequenceNumber,
        final Oslp.RegisterDeviceRequest registerRequest) throws UnknownHostException {

    final InetAddress inetAddress = InetAddress.getByAddress(registerRequest.getIpAddress().toByteArray());
    final String deviceType = registerRequest.getDeviceType().toString();
    final boolean hasSchedule = registerRequest.getHasSchedule();
    final String deviceIdentification = registerRequest.getDeviceIdentification();

    // Send message to OSGP-CORE to save IP Address, device type and has
    // schedule values in OSGP-CORE database.
    this.deviceRegistrationService.sendDeviceRegisterRequest(inetAddress, deviceType, hasSchedule,
            deviceIdentification);//  w w w. ja  v a 2  s .  c o  m

    OslpDevice oslpDevice = this.oslpDeviceSettingsService
            .getDeviceByDeviceIdentification(registerRequest.getDeviceIdentification());

    // Save the security related values in the OSLP database.
    oslpDevice.updateRegistrationData(deviceUid, registerRequest.getDeviceType().toString(),
            Integer.valueOf(registerRequest.getRandomDevice()));
    oslpDevice.setSequenceNumber(SequenceNumberUtils.convertByteArrayToInteger(sequenceNumber));
    oslpDevice = this.oslpDeviceSettingsService.updateDevice(oslpDevice);

    // Return current date and time in UTC so the device can sync the clock.
    final Oslp.RegisterDeviceResponse.Builder responseBuilder = Oslp.RegisterDeviceResponse.newBuilder()
            .setStatus(Oslp.Status.OK).setCurrentTime(Instant.now().toString(format))
            .setRandomDevice(registerRequest.getRandomDevice())
            .setRandomPlatform(oslpDevice.getRandomPlatform());

    // Return local time zone information of the platform. Devices can use
    // this to convert UTC times to local times.
    final LocationInfo.Builder locationInfo = LocationInfo.newBuilder();
    locationInfo.setTimeOffset(this.timeZoneOffsetMinutes);

    // Get the GPS values from OSGP-CORE database.
    final GpsCoordinatesDto gpsCoordinates = this.deviceDataService
            .getGpsCoordinatesForDevice(deviceIdentification);

    // Add GPS information when available in meta data.
    if (gpsCoordinates != null && gpsCoordinates.getLatitude() != null
            && gpsCoordinates.getLongitude() != null) {
        final int latitude = (int) ((gpsCoordinates.getLatitude()) * 1000000);
        final int longitude = (int) ((gpsCoordinates.getLongitude()) * 1000000);
        locationInfo.setLatitude(latitude).setLongitude(longitude);
    }

    responseBuilder.setLocationInfo(locationInfo);

    return Oslp.Message.newBuilder().setRegisterDeviceResponse(responseBuilder.build()).build();
}

From source file:at.alladin.rmbt.shared.Helperfunctions.java

public static String anonymizeIp(final InetAddress inetAddress) {
    try {//from w w  w .j a  va 2s  .  com
        final byte[] address = inetAddress.getAddress();
        address[address.length - 1] = 0;
        if (address.length > 4) // ipv6
        {
            for (int i = 6; i < address.length; i++)
                address[i] = 0;
        }

        String result = InetAddresses.toAddrString(InetAddress.getByAddress(address));
        if (address.length == 4)
            result = result.replaceFirst(".0$", "");
        return result;
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Discovery Process to identify Clusters with in 
 * network./*  w  w w .  ja  v  a  2 s  . com*/
 * 
 * @throws IOException if occurred during operation
 */
private void doDiscover() throws IOException {

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Wait for Response
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Receive
    resSock.setSoTimeout((int) TIMEOUT);
    try {
        resSock.receive(response);
    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    }

    byte[] data = response.getData();

    byte[] ipBytes = Arrays.copyOfRange(data, 0, 4);
    byte[] portBytes = Arrays.copyOfRange(data, 4, 9);

    InetAddress ip = InetAddress.getByAddress(ipBytes);
    StringBuilder sb = new StringBuilder(ip.getHostAddress());
    sb.append(":");
    for (byte b : portBytes) {
        sb.append(b);
    }

    this.cluster = sb.toString();
}

From source file:com.rovemonteux.silvertunnel.netlib.layer.tor.common.TCPStreamProperties.java

public InetAddress getAddr() {
    if (addr == null && hostname != null && !hostname.isEmpty() && InetAddressUtils.isIPv4Address(hostname)) {
        try {/*w w w .  j a va  2  s.c o m*/
            String[] octets = hostname.split("\\.");
            byte[] ip = new byte[4];
            ip[0] = (byte) Integer.parseInt(octets[0]);
            ip[1] = (byte) Integer.parseInt(octets[1]);
            ip[2] = (byte) Integer.parseInt(octets[2]);
            ip[3] = (byte) Integer.parseInt(octets[3]);
            return InetAddress.getByAddress(ip);
        } catch (UnknownHostException e) {
            return addr;
        }
    }
    return addr;
}