Example usage for java.net InetAddress toString

List of usage examples for java.net InetAddress toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts this IP address to a String .

Usage

From source file:org.apache.storm.daemon.ui.filters.AuthorizedUserFilter.java

@Override
public void filter(ContainerRequestContext containerRequestContext) {
    AuthNimbusOp annotation = resourceInfo.getResourceMethod().getAnnotation(AuthNimbusOp.class);
    if (annotation == null) {
        return;/*from  w w  w.  j  av a 2 s .co  m*/
    }
    String op = annotation.value();
    if (op == null) {
        return;
    }

    Map topoConf = null;
    if (annotation.needsTopoId()) {
        final String topoId = containerRequestContext.getUriInfo().getPathParameters().get("id").get(0);
        try (NimbusClient nimbusClient = NimbusClient.getConfiguredClient(conf)) {
            topoConf = (Map) JSONValue.parse(nimbusClient.getClient().getTopologyConf(topoId));
        } catch (AuthorizationException ae) {
            LOG.error("Nimbus isn't allowing {} to access the topology conf of {}. {}", ReqContext.context(),
                    topoId, ae.get_msg());
            containerRequestContext.abortWith(makeResponse(ae, containerRequestContext, 403));
            return;
        } catch (TException e) {
            LOG.error("Unable to fetch topo conf for {} due to ", topoId, e);
            containerRequestContext.abortWith(
                    makeResponse(new IOException("Unable to fetch topo conf for topo id " + topoId, e),
                            containerRequestContext, 500));
            return;
        }
    }

    ReqContext reqContext = ReqContext.context();

    if (reqContext.isImpersonating()) {
        if (uiImpersonationHandler != null) {
            if (!uiImpersonationHandler.permit(reqContext, op, topoConf)) {
                Principal realPrincipal = reqContext.realPrincipal();
                Principal principal = reqContext.principal();
                String user = "unknown";
                if (principal != null) {
                    user = principal.getName();
                }
                String realUser = "unknown";
                if (realPrincipal != null) {
                    realUser = realPrincipal.getName();
                }
                InetAddress remoteAddress = reqContext.remoteAddress();

                containerRequestContext.abortWith(makeResponse(
                        new AuthorizationException(
                                "user '" + realUser + "' is not authorized to impersonate user '" + user
                                        + "' from host '" + remoteAddress.toString() + "'. Please"
                                        + "see SECURITY.MD to learn how to configure impersonation ACL."),
                        containerRequestContext, 401));
                return;
            }

            LOG.warn(
                    " principal {} is trying to impersonate {} but {} has no authorizer configured. "
                            + "This is a potential security hole. Please see SECURITY.MD to learn how to "
                            + "configure an impersonation authorizer.",
                    reqContext.realPrincipal().toString(), reqContext.principal().toString(),
                    conf.get(DaemonConfig.NIMBUS_IMPERSONATION_AUTHORIZER));
        }
    }

    if (uiAclHandler != null) {
        if (!uiAclHandler.permit(reqContext, op, topoConf)) {
            Principal principal = reqContext.principal();
            String user = "unknown";
            if (principal != null) {
                user = principal.getName();
            }
            containerRequestContext.abortWith(makeResponse(
                    new AuthorizationException(
                            "UI request '" + op + "' for '" + user + "' user is not authorized"),
                    containerRequestContext, 403));
            return;
        }
    }
}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Create an ident server on port 113 with the specified encoding
 *
 * @param encoding Encoding to use for sockets
 *//* ww  w .ja va  2 s .co m*/
protected IdentServer(Charset encoding, InetAddress localAddress, int port) {
    try {
        this.encoding = encoding;
        this.localAddress = localAddress;
        this.serverSocket = new ServerSocket(port, 50, localAddress);
        this.port = port;
    } catch (Exception e) {
        throw new RuntimeException("Could not create server socket for IdentServer on "
                + localAddress.toString() + ", port " + port, e);
    }
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.SSLSocketChannelHandler.java

/**
 * Process the contents of the buffer. Give sub-classes a chance to override this behavior.
 *
 * @param sslSocketChannel the channel the data was read from
 * @param socketChannel the socket channel being wrapped by sslSocketChannel
 * @param bytesRead the number of bytes read
 * @param buffer the buffer to process/*from   www.j av a 2  s.co  m*/
 * @throws InterruptedException thrown if interrupted while queuing events
 */
protected void processBuffer(final SSLSocketChannel sslSocketChannel, final SocketChannel socketChannel,
        final int bytesRead, final byte[] buffer) throws InterruptedException, IOException {
    final InetAddress sender = socketChannel.socket().getInetAddress();

    // go through the buffer looking for the end of each message
    for (int i = 0; i < bytesRead; i++) {
        final byte currByte = buffer[i];

        // check if at end of a message
        if (currByte == getDelimiter()) {
            if (currBytes.size() > 0) {
                final SSLSocketChannelResponder response = new SSLSocketChannelResponder(socketChannel,
                        sslSocketChannel);
                final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString());
                final E event = eventFactory.create(currBytes.toByteArray(), metadata, response);
                events.offer(event);
                currBytes.reset();
            }
        } else {
            currBytes.write(currByte);
        }
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static InetAddress getFirstNonLoopbackLocalInetAddress() {
    final InetAddress[] addrs = getAllLocalInetAddresses();
    if (addrs != null) {
        for (final InetAddress addr : addrs) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info(/*from   w w w  .  j  ava2s.  c  o m*/
                        "Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
            }

            if (!addr.isLoopbackAddress()) {
                return addr;
            }
        }
    }

    s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length);
    return null;
}

From source file:org.coltram.nsd.bonjour.BonjourProcessor.java

public void callAction(JSONObject object, String serviceId, final AtomConnection connection, String callBack)
        throws JSONException {
    final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId);
    if (bonjourService == null) {
        log.info("no service with id " + serviceId + " in callAction");
        return;//from w  ww.  j  a va2s . co  m
    }
    if (bonjourService.isLocal()) {
        // find the LocalExposedBonjourService in question
        LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId);
        // send the info to that service
        object.put("originAtom", connection.getId());
        localcbs.notifyListeners(object.toString());
    } else {
        try {
            Socket socket = bonjourService.getSocket();
            int replyPort = -1;
            final InetAddress inetAddress = socket.getInetAddress();
            if (callBack != null) {
                // wait for reply on the same socket
                ServerSocket serverSocket = connection.getServerSocket();
                replyPort = serverSocket.getLocalPort();
                log.finer("start server for reply " + serverSocket.getLocalPort());
                new Thread(new ReplyListener(serverSocket, connection.getConnection())).start();
                Thread.yield();
            }
            String ia = inetAddress.toString();
            if (ia.startsWith("/")) {
                ia = ia.substring(1);
            }
            object.put("address", LocalHost.name);
            object.put("replyPort", replyPort + "");
            object.put("originAtom", connection.getId());
            DataOutputStream dos = bonjourService.getSocketDOS();
            dos.writeBytes(object.toString() + "\n");
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:ca.farrelltonsolar.classic.ModbusTask.java

public boolean connect() throws UnknownHostException {
    boolean rVal = false;
    InetAddress inetAddress = InetAddress.getByName(chargeControllerInfo.deviceIpAddress());
    Log.d(getClass().getName(),//from w  w w  .j  a v a  2  s.c  o m
            String.format("Connecting to %s  (%s)", chargeControllerInfo.toString(), inetAddress.toString()));
    try {
        disconnect();
        modbusMaster = new ModbusTCPMaster(chargeControllerInfo.deviceIpAddress(), chargeControllerInfo.port());

        modbusMaster.connect();
        if (modbusMaster.isConnected()) {
            rVal = true;
        }
    } catch (Exception e1) {
        Log.w(getClass().getName(),
                String.format("Could not connect to %s, ex: %s", chargeControllerInfo.toString(), e1));
        e1.printStackTrace();
        modbusMaster = null;
        MonitorApplication.chargeControllers().setReachable(chargeControllerInfo.deviceIpAddress(),
                chargeControllerInfo.port(), false);
    }
    return rVal;
}

From source file:org.mythtv.client.ui.MainMenuFragment.java

/**
 * @throws IOException/*  w  ww. j  a v  a  2 s  . c  om*/
 */
private void startProbe() throws IOException {
    Log.v(TAG, "startProbe : enter");

    if (zeroConf != null) {
        stopProbe();
    }

    // figure out our wifi address, otherwise bail
    WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    WifiInfo wifiinfo = wifi.getConnectionInfo();
    int intaddr = wifiinfo.getIpAddress();

    byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
            (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
    InetAddress addr = InetAddress.getByAddress(byteaddr);
    Log.d(TAG, "startProbe : wifi address=" + addr.toString());

    // start multicast lock
    mLock = wifi.createMulticastLock("mythtv_lock");
    mLock.setReferenceCounted(true);
    mLock.acquire();

    zeroConf = JmDNS.create(addr, HOSTNAME);
    zeroConf.addServiceListener(MYTHTV_FRONTEND_TYPE, this);

    Log.v(TAG, "startProbe : exit");
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.StandardSocketChannelHandler.java

/**
 * Process the contents that have been read into the buffer. Allow sub-classes to override this behavior.
 *
 * @param socketChannel the channel the data was read from
 * @param socketBuffer the buffer the data was read into
 * @throws InterruptedException if interrupted when queuing events
 *///from w w  w . j av a  2 s. c  om
protected void processBuffer(final SocketChannel socketChannel, final ByteBuffer socketBuffer)
        throws InterruptedException, IOException {
    // get total bytes in buffer
    final int total = socketBuffer.remaining();
    final InetAddress sender = socketChannel.socket().getInetAddress();

    // go through the buffer looking for the end of each message
    currBytes.reset();
    for (int i = 0; i < total; i++) {
        // NOTE: For higher throughput, the looking for \n and copying into the byte stream could be improved
        // Pull data out of buffer and cram into byte array
        byte currByte = socketBuffer.get();

        // check if at end of a message
        if (currByte == getDelimiter()) {
            if (currBytes.size() > 0) {
                final SocketChannelResponder response = new SocketChannelResponder(socketChannel);
                final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString());
                final E event = eventFactory.create(currBytes.toByteArray(), metadata, response);
                events.offer(event);
                currBytes.reset();

                // Mark this as the start of the next message
                socketBuffer.mark();
            }
        } else {
            currBytes.write(currByte);
        }
    }
}

From source file:org.jkcsoft.java.util.JavaHelper.java

public static InetAddress getUsefulInetAddr() throws UnknownHostException {
    InetAddress returnInetAddr = InetAddress.getLocalHost();
    int usefulCount = 0;
    try {/*  w w w.j a va  2  s  .  co  m*/
        Enumeration niEnum = NetworkInterface.getNetworkInterfaces();
        while (niEnum.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) niEnum.nextElement();
            Enumeration ieEnum = ni.getInetAddresses();
            while (ieEnum.hasMoreElements()) {
                InetAddress inetAddr = InetAddress.getLocalHost();
                inetAddr = (InetAddress) ieEnum.nextElement();
                log.debug("NIC [" + ni.getDisplayName() + "]" + " Addr hn=[" + inetAddr.getHostName() + "]"
                        + " chn=[" + inetAddr.getCanonicalHostName() + "]" + " ha=[" + inetAddr.getHostAddress()
                        + "]");
                // hack to skip addresses often provided by Linux...
                if (!"127.0.0.1".equals(inetAddr.getHostAddress())
                        && inetAddr.getHostAddress().indexOf(':') == -1) {
                    if (usefulCount == 0)
                        returnInetAddr = inetAddr;
                    usefulCount++;
                } else {
                    // 
                }
            }
        }
    } catch (SocketException e) {
        log.error("getHostName", e);
    }

    if (usefulCount == 0) {
        log.warn("Only the loopback InetAddress could be found");
    }
    if (usefulCount > 1) {
        log.warn("More than one non-loopback InetAddrss was found; using the first one found.");
    }

    log.debug("Returning inet addr [" + returnInetAddr.toString() + "]");
    return returnInetAddr;
}

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override//from  ww  w  . j  av  a  2 s  . c  om
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}