Example usage for java.net Socket getLocalAddress

List of usage examples for java.net Socket getLocalAddress

Introduction

In this page you can find the example usage for java.net Socket getLocalAddress.

Prototype

public InetAddress getLocalAddress() 

Source Link

Document

Gets the local address to which the socket is bound.

Usage

From source file:com.hazelcast.stabilizer.Utils.java

public static String getHostAddress() {
    if (hostAddress != null) {
        return hostAddress;
    }//w w w.jav  a  2s. com

    synchronized (Utils.class) {
        try {
            if (hostAddress != null) {
                return hostAddress;
            }
            Socket s = new Socket("google.com", 80);
            hostAddress = s.getLocalAddress().getHostAddress();
            s.close();
            return hostAddress;
        } catch (IOException io) {
            throw new RuntimeException(io);
        }
    }
}

From source file:org.wso2.carbon.databridge.agent.endpoint.binary.BinaryClientPoolFactory.java

@Override
public void terminateClient(Object client) {
    Socket socket = null;
    try {//from   w w w.  j  a v a  2s .c om
        socket = (Socket) client;
        socket.close();
    } catch (IOException e) {
        log.warn("Cannot close the socket successfully from " + socket.getLocalAddress().getHostAddress() + ":"
                + socket.getPort());
    }
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test
public void shouldCreateSocketWithGivenLocalAddressAndPort() throws Exception {
    // Given/*from   ww w.j  a v a 2s .  c om*/
    InetAddress localAddress = InetAddress.getLoopbackAddress();
    int localPort = 28080;
    // When
    Socket sslSocket = socketFactory.createSocket("localhost", 18080, localAddress, localPort,
            new HttpConnectionParams());
    // Then
    assertThat(sslSocket.getLocalAddress(), is(equalTo(localAddress)));
    assertThat(sslSocket.getLocalPort(), is(equalTo(localPort)));
}

From source file:org.columba.core.main.ColumbaServer.java

/**
 * Handles a client connect and authentication.
 *///from  w  ww.  j av  a 2s  .  c o  m
protected void handleClient(Socket client) {
    try {
        // only accept client from local machine
        String host = client.getLocalAddress().getHostAddress();
        if (!(host.equals("127.0.0.1"))) {
            // client isn't from local machine
            return;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String line = reader.readLine();
        if (!line.startsWith("Columba ")) {
            return;
        }

        line = reader.readLine();
        if (!line.startsWith("User ")) {
            return;
        }

        PrintWriter writer = new PrintWriter(client.getOutputStream());
        if (!line.substring(5).equals(System.getProperty("user.name", ANONYMOUS_USER))) {
            writer.write("WRONG USER\r\n");
            writer.close();
            return;
        }
        writer.write("\r\n");
        writer.flush();

        line = reader.readLine();
        // do something with the arguments..
        List<String> list = new LinkedList<String>();
        StringTokenizer st = new StringTokenizer(line, "%");
        while (st.hasMoreTokens()) {
            String tok = (String) st.nextToken();
            list.add(tok);
        }

        try {
            CommandLine commandLine = ColumbaCmdLineParser.getInstance()
                    .parse((String[]) list.toArray(new String[0]));

            ComponentManager.getInstance().handleCommandLineParameters(commandLine);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            client.close();
        } catch (IOException ioe) {
        }
    }
}

From source file:net.NetUtils.java

/**
 * This is a drop-in replacement for /*from   w w  w.  j  a  va  2 s.com*/
 * {@link Socket#connect(SocketAddress, int)}.
 * In the case of normal sockets that don't have associated channels, this 
 * just invokes <code>socket.connect(endpoint, timeout)</code>. If 
 * <code>socket.getChannel()</code> returns a non-null channel,
 * connect is implemented using Hadoop's selectors. This is done mainly
 * to avoid Sun's connect implementation from creating thread-local 
 * selectors, since Hadoop does not have control on when these are closed
 * and could end up taking all the available file descriptors.
 * 
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * 
 * @param socket
 * @param endpoint 
 * @param timeout - timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:org.apache.hadoop.net.TestNetUtils.java

/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.//ww  w .  j  ava  2s  . c o m
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
    Configuration conf = new Configuration();

    Socket socket = NetUtils.getDefaultSocketFactory(conf).createSocket();
    socket.bind(new InetSocketAddress("localhost", 0));
    System.err.println("local address: " + socket.getLocalAddress());
    System.err.println("local port: " + socket.getLocalPort());
    try {
        NetUtils.connect(socket, new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()), 20000);
        socket.close();
        fail("Should not have connected");
    } catch (ConnectException ce) {
        System.err.println("Got exception: " + ce);
        assertTrue(ce.getMessage().contains("resulted in a loopback"));
    } catch (SocketException se) {
        // Some TCP stacks will actually throw their own Invalid argument
        // exception here. This is also OK.
        assertTrue(se.getMessage().contains("Invalid argument"));
    }
}

From source file:com.csipsimple.wizards.impl.MondotalkCreate.java

private boolean retrieveCaptcha() {
    String ip;/*from   w  ww.jav  a2s .c  o m*/
    try {
        Socket socket = new Socket("api001.mondotalk.com", 80);
        ip = socket.getLocalAddress().toString();
    } catch (Exception e) {
        Log.e(THIS_FILE, "Can't get local ip address", e);
        ip = "127.0.0.1";
    }

    try {
        // No SOAP lib.... bourrinage !
        String requestURL = "https://api001.mondotalk.com/webservices/captcha.php";

        HttpPost httpPost = new HttpPost(requestURL);
        httpPost.addHeader("SOAPAction", "\"Captcha\"");
        httpPost.addHeader("Content-Type", "text/xml");

        // prepare POST body
        String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope "
                + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" "
                + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\""
                + " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" "
                + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""
                + " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\" >" + "<SOAP-ENV:Body>"
                + "<Captcha SOAP-ENC:root=\"1\">" + "<v1 xsi:type=\"xsd:string\">" + API_KEY + "</v1>"
                + "<v2 xsi:type=\"xsd:string\">" + ip + "</v2>" + "<v3 xsi:type=\"xsd:string\">520</v3>"
                + "<v4 xsi:type=\"xsd:string\">200</v4>" + "</Captcha>" + "</SOAP-ENV:Body>"
                + "</SOAP-ENV:Envelope>";

        // set POST body
        HttpEntity entity;
        entity = new StringEntity(body);
        httpPost.setEntity(entity);

        HttpClient httpClient = new DefaultHttpClient();
        // Create a response handler
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent());
            BufferedReader br = new BufferedReader(isr);

            String line = null;
            while ((line = br.readLine()) != null) {
                if (!TextUtils.isEmpty(line)) {

                    Matcher matcher = soapResultPattern.matcher(line);
                    if (matcher.matches()) {
                        String strValue = matcher.group(1).trim();
                        if (!TextUtils.isEmpty(strValue)) {
                            String[] strValues = strValue.split("\\|");
                            if (strValues.length > 1) {
                                captchaUrl = strValues[0];
                                captchaKey = strValues[1];
                            }
                        }
                        break;
                    }
                }
            }

            if (TextUtils.isEmpty(captchaKey)) {
                return false;
            }

            Log.d(THIS_FILE, "Captcha retrieved " + captchaKey + " and " + captchaUrl);

            captchaBitmap = BitmapFactory.decodeStream((new URL(captchaUrl)).openConnection().getInputStream());

            mHander.sendEmptyMessage(MSG_CAPTCHA_LOADED);
        } else {
            Log.e(THIS_FILE, "Something went wrong while retrieving the captcha webservice ");
        }

    } catch (Exception e) {
        Log.e(THIS_FILE, "Something went wrong while retrieving the captcha", e);
    }

    return false;
}

From source file:at.alladin.rmbt.android.util.CheckIpTask.java

@Override
protected JSONArray doInBackground(final Void... params) {
    needsRetry = false;/*ww  w  .  j  av a 2s.c  om*/
    serverConn = new ControlServerConnection(activity);

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv4(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv4 = s.getLocalAddress();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv6(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv6 = s.getLocalAddress();
        s.close();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        needsRetry = ConfigHelper.isRetryRequiredOnIpv6SocketTimeout(activity);
    } catch (Exception e) {
        needsRetry = false;
        e.printStackTrace();
    }

    newsList = new JSONArray();

    if (privateIpv4 != null) {
        JSONArray response = serverConn.requestIp(false);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv4 found");
    }

    if (privateIpv6 != null) {
        JSONArray response = serverConn.requestIp(true);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv6 found");
    }

    return newsList;
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java

@Override
public Response execute(Request request) throws IOException {
    HttpMethod http = null;//from w w w  .j ava2  s  . c om

    switch (request.method()) {
    case DELETE:
        http = new DeleteMethodWithBody();
        break;
    case HEAD:
        http = new HeadMethod();
        break;
    case GET:
        http = (request.body() == null ? new GetMethod() : new GetMethodWithBody());
        break;
    case POST:
        http = new PostMethod();
        break;
    case PUT:
        http = new PutMethod();
        break;

    default:
        throw new EsHadoopTransportException("Unknown request method " + request.method());
    }

    CharSequence uri = request.uri();
    if (StringUtils.hasText(uri)) {
        http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false));
    }
    // NB: initialize the path _after_ the URI otherwise the path gets reset to /
    http.setPath(prefixPath(request.path().toString()));

    try {
        // validate new URI
        uri = http.getURI().toString();
    } catch (URIException uriex) {
        throw new EsHadoopTransportException("Invalid target URI " + request, uriex);
    }

    CharSequence params = request.params();
    if (StringUtils.hasText(params)) {
        http.setQueryString(params.toString());
    }

    ByteSequence ba = request.body();
    if (ba != null && ba.length() > 0) {
        if (!(http instanceof EntityEnclosingMethod)) {
            throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug",
                    request.method().name()));
        }
        EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http;
        entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba));
        entityMethod.setContentChunked(false);
    }

    // when tracing, log everything
    if (log.isTraceEnabled()) {
        log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(),
                httpInfo, request.path(), request.body()));
    }

    long start = System.currentTimeMillis();
    try {
        client.executeMethod(http);
    } finally {
        stats.netTotalTime += (System.currentTimeMillis() - start);
    }

    if (log.isTraceEnabled()) {
        Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null);
        String addr = sk.getLocalAddress().getHostAddress();
        log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(),
                HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString()));
    }

    // the request URI is not set (since it is retried across hosts), so use the http info instead for source
    return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo);
}

From source file:com.summit.jbeacon.buoys.MultiCastResourceBuoy.java

private InetAddress guessHostAddress(final Socket socket) throws MultiCastResourceBuoyException {
    return socket.getLocalAddress();
}