Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

In this page you can find the example usage for java.net InetSocketAddress getAddress.

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:edu.umass.cs.msocket.gns.GnsIntegration.java

/**
 * Remove a specific IP address from the list of IPs associated with the
 * MServerSocket that has the given Human Readable Name
 * /*from  w  w w  .j a v  a 2  s  . c o  m*/
 * @param name Human readable name of the MServerSocket
 * @param saddr address to remove from the GNS
 * @param gnsCredentials GNS credentials to use
 * @throws Exception
 */
public static void unregisterWithGNS(String name, InetSocketAddress saddr, GnsCredentials gnsCredentials)
        throws Exception {
    if (gnsCredentials == null)
        gnsCredentials = GnsCredentials.getDefaultCredentials();

    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    GuidEntry socketGuid = KeyPairUtils
            .getGuidEntryFromPreferences(gnsCredentials.getGnsHost() + ":" + gnsCredentials.getGnsPort(), name);
    String ipPort = saddr.getAddress().getHostAddress() + ":" + saddr.getPort();

    // If all GNS accesses are synchronized on this object, we shouldn't have a
    // concurrency issue while updating
    synchronized (gnsClient) {
        JSONArray currentIPs = gnsClient.fieldRead(socketGuid.getGuid(), GnsConstants.SERVER_REG_ADDR,
                gnsCredentials.getGuidEntry());
        JSONArray newIPs = new JSONArray();
        int idx = -1;
        for (int i = 0; i < currentIPs.length(); i++) {
            if (ipPort.equals(currentIPs.getString(i))) {
                idx = i;
                //break;
            } else {
                newIPs.put(currentIPs.getString(i));
            }
        }
        if (idx != -1) {
            //currentIPs.remove(idx);
            gnsClient.fieldReplace(socketGuid.getGuid(), GnsConstants.SERVER_REG_ADDR, newIPs,
                    gnsCredentials.getGuidEntry());
        }
    }

}

From source file:org.apache.hadoop.security.SecurityUtil.java

/**
 * Construct the service key for a token
 * @param addr InetSocketAddress of remote connection with a token
 * @return "ip:port" or "host:port" depending on the value of
 *          hadoop.security.token.service.use_ip
 *//*ww w  .  j av  a 2  s  .c  om*/
public static Text buildTokenService(InetSocketAddress addr) {
    String host = null;
    if (useIpForTokenService) {
        if (addr.isUnresolved()) { // host has no ip address
            throw new IllegalArgumentException(new UnknownHostException(addr.getHostName()));
        }
        host = addr.getAddress().getHostAddress();
    } else {
        host = addr.getHostName().toLowerCase();
    }
    return new Text(host + ":" + addr.getPort());
}

From source file:org.cloudata.core.commitlog.ServerLocationManager.java

static String getStringAddrFrom(InetSocketAddress addr) {
    return addr.getAddress().getHostAddress() + ":" + addr.getPort();
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Returns an InetSocketAddress that a client can use to connect to the given listening address.
 *
 * @param addr of a listener/*from ww w. ja  v  a  2s .c  o  m*/
 *
 * @return socket address that a client can use to connect to the server.
 */
public static InetSocketAddress getConnectAddress(InetSocketAddress addr) {
    if (!addr.isUnresolved() && addr.getAddress().isAnyLocalAddress()) {
        try {
            addr = new InetSocketAddress(InetAddress.getLocalHost(), addr.getPort());
        } catch (UnknownHostException uhe) {
            // shouldn't get here unless the host doesn't have a loopback iface
            addr = createSocketAddrForHost("127.0.0.1", addr.getPort());
        }
    }
    return addr;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java

public static void configureProxy(AbstractHttpClient client, RepositoryLocation location) {
    Assert.isNotNull(client);/*from   w w w.ja va2s  . c o  m*/
    Assert.isNotNull(location);
    String url = location.getUrl();
    Assert.isNotNull(url, "The location url must not be null"); //$NON-NLS-1$

    String host = NetUtil.getHost(url);
    Proxy proxy;
    if (NetUtil.isUrlHttps(url)) {
        proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
    } else {
        proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
    }

    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();

        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(address.getHostName(), address.getPort()));

        if (proxy instanceof AuthenticatedProxy) {
            AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
            Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
                    address.getAddress(), false);
            if (credentials instanceof NTCredentials) {
                AuthScope proxyAuthScopeNTLM = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM, AuthPolicy.NTLM);
                client.getCredentialsProvider().setCredentials(proxyAuthScopeNTLM, credentials);

                AuthScope proxyAuthScopeAny = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM);
                Credentials usernamePasswordCredentials = getCredentials(authProxy.getUserName(),
                        authProxy.getPassword(), address.getAddress(), true);
                client.getCredentialsProvider().setCredentials(proxyAuthScopeAny, usernamePasswordCredentials);

            } else {
                AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM);
                client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials);
            }
        }
    } else {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static String getSocketConnectString(InetSocketAddress socketAddress) {
    String host;/*  ww  w .  ja  va2s  .  c  o  m*/
    InetAddress address = socketAddress.getAddress();
    if (address == null) {
        host = socketAddress.getHostString();
    } else if (address.isAnyLocalAddress() || address.isLoopbackAddress()) {
        host = address.getCanonicalHostName();
    } else {
        host = address.getHostName();
    }
    return host + ":" + socketAddress.getPort();
}

From source file:com.buaa.cfs.utils.SecurityUtil.java

/**
 * Construct the service key for a token
 *
 * @param addr InetSocketAddress of remote connection with a token
 *
 * @return "ip:port" or "host:port" depending on the value of hadoop.security.token.service.use_ip
 *//*from  www .  java  2s. c  om*/
public static Text buildTokenService(InetSocketAddress addr) {
    String host = null;
    if (useIpForTokenService) {
        if (addr.isUnresolved()) { // host has no ip address
            throw new IllegalArgumentException(new UnknownHostException(addr.getHostName()));
        }
        host = addr.getAddress().getHostAddress();
    } else {
        host = StringUtils.toLowerCase(addr.getHostName());
    }
    return new Text(host + ":" + addr.getPort());
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {//from   w  ww .ja  va2  s  . co m
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go
                if (packet.remaining() < 4
                        || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) {
                    return;
                }

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                ByteBuffer outBuf = ByteBuffer.allocate(1100);
                MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0,
                        InetAddress.getByName("::"), 0L);
                mpr.dump(outBuf, bindMap.get(channel));
                outBuf.flip();

                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) {
    rmId = (rmId == null) ? "" : ("." + rmId);
    InetSocketAddress address;//from   w  ww .jav  a 2 s  .  c o m
    if (sslEnabled) {
        address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId,
                YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS,
                YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT);
    } else {
        address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId,
                YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT);
    }
    LOG.info("rm webapp address setting {}", address);
    LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS));
    InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address);
    InetAddress resolved = resolvedSocketAddress.getAddress();
    if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) {
        try {
            resolvedSocketAddress = InetSocketAddress
                    .createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort());
        } catch (UnknownHostException e) {
            //Ignore and fallback.
        }
    }
    return resolvedSocketAddress;
}

From source file:org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster.java

public static String getResolvedMRHistoryWebAppURLWithoutScheme(Configuration conf, boolean isSSLEnabled) {
    InetSocketAddress address = null;
    if (isSSLEnabled) {
        address = conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_PORT);
    } else {//from w  w  w .  ja  va  2s  . c  om
        address = conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_PORT);
    }
    address = NetUtils.getConnectAddress(address);
    StringBuffer sb = new StringBuffer();
    InetAddress resolved = address.getAddress();
    if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) {
        String lh = address.getHostName();
        try {
            lh = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            //Ignore and fallback.
        }
        sb.append(lh);
    } else {
        sb.append(address.getHostName());
    }
    sb.append(":").append(address.getPort());
    return sb.toString();
}