Example usage for java.net Inet4Address getHostAddress

List of usage examples for java.net Inet4Address getHostAddress

Introduction

In this page you can find the example usage for java.net Inet4Address getHostAddress.

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation form.

Usage

From source file:uk.ac.horizon.ubihelper.j2se.Server.java

/**
 * @param args/* ww  w .  j  av  a  2s .  c o  m*/
 */
public static void main(String[] args) {
    InetAddress bestAddress = null;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            if (!ni.isUp() || ni.isVirtual() || ni.isLoopback())
                continue;
            logger.info("Has interface " + ni.getName() + ": " + ni.getDisplayName());
            Enumeration<InetAddress> as = ni.getInetAddresses();
            while (as.hasMoreElements()) {
                InetAddress a = as.nextElement();
                if (a instanceof Inet4Address) {
                    Inet4Address ip = (Inet4Address) a;
                    logger.info("- IPv4 address " + ip.getHostAddress());
                    if (ip.isSiteLocalAddress()) {
                        logger.info("-- site local!");
                        if (bestAddress == null)
                            bestAddress = ip;
                    } else
                        bestAddress = ip;
                }
            }
        }
    } catch (Exception e) {
        logger.severe("Could not list NetworkInterfaces: " + e);
        System.exit(-1);
    }
    if (bestAddress == null) {
        logger.severe("Could not find an IP address to bind to - using localhost");
        try {
            bestAddress = InetAddress.getLocalHost();
        } catch (Exception e) {
            logger.severe("Could not get localhost address: " + e);
            System.exit(-2);
        }
    }
    int port = 0;
    if (args.length == 1) {
        try {
            port = Integer.parseInt(args[0]);
        } catch (NumberFormatException nfe) {
            System.err.println("Usage: <server-port>");
            System.exit(-3);
        }
    }
    Server server = new Server();
    server.init(bestAddress, port);
}

From source file:org.apache.marmotta.platform.security.util.IPv4SubnetInfo.java

public IPv4SubnetInfo(Inet4Address address, int netmask) {
    apacheInfo = new SubnetUtils(address.getHostAddress() + "/" + netmask).getInfo();
}

From source file:net.sf.jasperreports.phantomjs.PhantomJSProcess.java

private URI listenURI(Inet4Address listenAddress, int listenPort) {
    try {/*from   w w  w  . j  a v  a2  s  .  c  o m*/
        return new URI("http", null, listenAddress.getHostAddress(), listenPort, null, null, null);
    } catch (URISyntaxException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:net.fenyo.gnetwatch.targets.TargetIPv4Range.java

/**
 * Constructor.//from   w  ww  . j a va 2  s .c om
 * @param name target name.
 * @param begin first address.
 * @param end last address.
 * @throws AlgorithmException exception.
 */
// GUI thread
public TargetIPv4Range(final String name, final Inet4Address begin, final Inet4Address end)
        throws AlgorithmException {
    super(name);
    if (begin == null || end == null)
        throw new AlgorithmException("begin or end is null");
    this.begin = begin;
    this.end = end;
    setItem(begin.getHostAddress() + "-" + end.getHostAddress());
}

From source file:net.fenyo.gnetwatch.targets.TargetIPv4Subnet.java

/**
 * Constructor.// ww w.j  a  v  a 2 s . com
 * @param name target name.
 * @param network network address.
 * @param netmask netmask value.
 * @throws AlgorithmException exception.
 */
// GUI thread
public TargetIPv4Subnet(final String name, final Inet4Address network, final Inet4Address netmask)
        throws AlgorithmException {
    super(name);
    if (network == null || netmask == null)
        throw new AlgorithmException("network or netmask is null");
    this.network = network;
    this.netmask = netmask;
    setItem(network.getHostAddress() + "/" + netmask.getHostAddress());
}

From source file:eu.smartenit.unada.tpm.TopologyProximityMonitorImpl.java

/**
 * OS-independent traceroute executor to specified address.
 *
 * @param address destination host.//from   ww  w .ja  va2 s.  co m
 * @return Traceroute output.
 * @throws IOException If an I/O error occurs
 * @throws InterruptedException if the current thread is
 * {@linkplain Thread#interrupt() interrupted} by another thread while it is
 * waiting, then the wait is ended and an {@link InterruptedException} is
 * thrown.
 */
public List<String> executeTraceroute(Inet4Address address) throws IOException, InterruptedException {
    logger.debug("Executing traceroute");
    String command;
    if (IS_WINDOWS) {
        command = String.format(WINDOWS_TRACEROUTE_COMMAND, address.getHostAddress());
    } else if (IS_LINUX) {
        command = String.format(LINUX_TRACEROUTE_COMMAND, address.getHostAddress());
    } else {
        throw new UnsupportedOperationException("OS is neither Windows nor Linux (os.name = \"" + OS + "\")");
    }
    Process proc = Runtime.getRuntime().exec(command, new String[] { "LC_ALL=C" });
    BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String line;
    String error = "";
    while ((line = stderr.readLine()) != null) {
        error = error + line + "\n";
    }
    if (!error.isEmpty()) {
        throw new RuntimeException("Error while executing \"" + command + "\": " + error);
    }

    proc.waitFor();

    List<String> result = new ArrayList<>();
    while ((line = stdout.readLine()) != null) {
        result.add(line);
    }
    logger.debug("Traceroute finished");
    return result;
}

From source file:net.fenyo.gnetwatch.targets.TargetIPv4.java

/**
* Constructor.//from   ww  w .ja  v a2 s  . com
* @param name target name.
* @param address IPv4 address.
* @param SNMPManager snmp manager.
* @throws AlgorithmException exception.
*/
// GUI thread
public TargetIPv4(final String name, final Inet4Address address, final SNMPManager snmp_manager)
        throws AlgorithmException {
    super(name);
    if (address == null)
        throw new AlgorithmException("address is null");
    this.address = address;
    snmp_querier = snmp_manager != null ? snmp_manager.getQuerier(address) : null;
    setItem(address.getHostAddress());
    ip_querier = new IPQuerier(address);
    // may last a long time (DNS resolver)
    // setDescription(address.getCanonicalHostName());
}

From source file:org.peercast.pecaport.AddMappingDialog.java

public AddMappingDialog(Context c, int pecaRunningPort, Collection<WanConnection> connected,
        final Inet4Address clientIp, final Listener listener) {

    String port, description;/*from  ww w . j  av a 2s . c  o  m*/
    if (pecaRunningPort > 0) {
        port = pecaRunningPort + "";
        description = PecaPortService.DESCRIPTION;
    } else {
        port = "";
        String modelName = StringUtils.substring(Build.MODEL, 0, 16);
        description = String.format("PecaPort(%s)", modelName);
    }

    View view = LayoutInflater.from(c).inflate(R.layout.add_port_dialog, null);
    vPrivateIp = (TextView) view.findViewById(R.id.vPrivateIp);
    vPrivateIp.setText(clientIp.getHostAddress());

    vConnections = (Spinner) view.findViewById(R.id.vConnections);

    vExternalPort = (EditText) view.findViewById(R.id.vExternalPort);
    vExternalPort.addTextChangedListener(mValidPortWatcher);
    vExternalPort.setText(port);

    vInternalPort = (EditText) view.findViewById(R.id.vInternalPort);
    vInternalPort.setText(vExternalPort.getText());
    vInternalPort.addTextChangedListener(mValidPortWatcher);

    vSomePort = (CheckBox) view.findViewById(R.id.vSamePort);
    vSomePort.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                vInternalPort.setText(vExternalPort.getText());
                vInternalPort.setEnabled(false);
            } else {
                vInternalPort.setEnabled(true);
            }
        }
    });
    vExternalPort.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (vSomePort.isChecked()) {
                vInternalPort.setText(vExternalPort.getText());
            }
        }
    });

    vTcp = (RadioButton) view.findViewById(R.id.vTcp);
    vDescription = (EditText) view.findViewById(R.id.vDescription);

    vDescription.setText(description);

    WanConnectionsAdapter wanAdapter = new WanConnectionsAdapter();

    wanAdapter.setConnections(connected);
    vConnections.setAdapter(wanAdapter);

    mBuilder = new AlertDialog.Builder(c).setTitle(R.string.t_add_port).setView(view)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    PortMapping mapping = new PortMapping();
                    mapping.setExternalPort(toUI2Bytes(vExternalPort));
                    mapping.setInternalPort(toUI2Bytes(vInternalPort));
                    mapping.setDescription(vDescription.getText().toString());
                    mapping.setInternalClient(vPrivateIp.getText().toString());
                    mapping.setEnabled(true);
                    mapping.setProtocol(vTcp.isChecked() ? PortMapping.Protocol.TCP : PortMapping.Protocol.UDP);
                    listener.onOkClick((WanConnection) vConnections.getSelectedItem(), mapping);
                }
            }).setIcon(R.drawable.ic_plus_box).setNegativeButton(android.R.string.cancel, null)
            .setCancelable(false);
}

From source file:com.entertailion.java.fling.FlingFrame.java

/**
 * Send a uri to the ChromeCast device//from  w  w w.  ja v a  2  s .  com
 * 
 * @param keycode
 */
protected void sendMediaUrl(String file) {
    if (selectedDialServer == null) {
        JOptionPane.showMessageDialog(this, resourceBundle.getString("device.select"));
        return;
    }
    isTranscoding = false;
    Log.d(LOG_TAG, "sendMediaUrl=" + file);
    if (file != null) {
        duration = 0;
        boolean found = false;
        String[] extensions = transcodingExtensionValues.split(",");
        for (String extension : extensions) {
            if (file.endsWith(extension.trim())) {
                found = true;
                break;
            }
        }
        if (!found) {
            try {
                int pos = file.lastIndexOf('.');
                String extension = "";
                if (pos > -1) {
                    extension = file.substring(pos);
                }
                Inet4Address address = getNetworAddress();
                if (address != null) {
                    final String url = "http://" + address.getHostAddress() + ":" + port + "/video" + extension;
                    if (!rampClient.isClosed()) {
                        rampClient.stop();
                    }
                    rampClient.launchApp(appId == null ? APP_ID : appId, selectedDialServer);
                    // wait for socket to be ready...
                    new Thread(new Runnable() {
                        public void run() {
                            while (!rampClient.isStarted() && !rampClient.isClosed()) {
                                try {
                                    // make less than 3 second ping time
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                }
                            }
                            if (!rampClient.isClosed()) {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                }
                                rampClient.load(url);
                            }
                        }
                    }).start();
                } else {
                    Log.d(LOG_TAG, "could not find a network interface");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            vlcTranscode(file);
        }

        // TODO
        if (!volume.getValueIsAdjusting()) {
            int position = (int) volume.getValue();
            // rampClient.volume(position / 100.0f);
        }
    }
}

From source file:com.entertailion.java.fling.FlingFrame.java

protected void vlcTranscode(final String file) {
    // Transcoding does not support jumps
    isTranscoding = true;/*from   w w w  . j  a  va2  s.c  o  m*/

    // http://caprica.github.io/vlcj/javadoc/2.1.0/index.html
    try {
        // clean up previous session
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        if (mediaPlayerFactory != null) {
            mediaPlayerFactory.release();
        }
        mediaPlayerFactory = new MediaPlayerFactory();
        mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
        // Add a component to be notified of player events
        mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
            public void opening(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Opening");
            }

            public void buffering(MediaPlayer mediaPlayer, float newCache) {
                Log.d(LOG_TAG, "VLC Transcoding: Buffering");
            }

            public void playing(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Playing");

                setDuration((int) (mediaPlayer.getLength() / 1000.0f));
                Log.d(LOG_TAG, "duration=" + duration);
            }

            public void paused(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Paused");
            }

            public void stopped(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Stopped");
            }

            public void finished(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Finished");
            }

            public void error(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Error");
            }

            public void videoOutput(MediaPlayer mediaPlayer, int newCount) {
                Log.d(LOG_TAG, "VLC Transcoding: VideoOutput");
            }
        });

        // Find a port for VLC HTTP server
        boolean started = false;
        int vlcPort = port + 1;
        while (!started) {
            try {
                ServerSocket serverSocket = new ServerSocket(vlcPort);
                Log.d(LOG_TAG, "Available port for VLC: " + vlcPort);
                started = true;
                serverSocket.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                vlcPort++;
            } catch (Exception ex) {
                break;
            }
        }

        if (!rampClient.isClosed()) {
            rampClient.stop();
        }
        Inet4Address address = getNetworAddress();
        if (address != null) {
            // Play a particular item, with options if necessary
            final String options[] = { ":sout=#transcode{" + transcodingParameterValues
                    + "}:http{mux=webm,dst=:" + vlcPort + "/cast.webm}", ":sout-keep" };
            // http://192.168.0.8:8087/cast.webm
            final String url = "http://" + address.getHostAddress() + ":" + vlcPort + "/cast.webm";
            Log.d(LOG_TAG, "url=" + url);
            if (true || isChromeCast()) {
                rampClient.launchApp(appId == null ? APP_ID : appId, selectedDialServer);
                // wait for socket to be ready...
                new Thread(new Runnable() {
                    public void run() {
                        while (!rampClient.isStarted() && !rampClient.isClosed()) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                            }
                        }
                        if (!rampClient.isClosed()) {
                            mediaPlayer.playMedia(file, options);
                            rampClient.load(url);
                        }
                    }
                }).start();
            } else {
                rampClient.load(url);
            }
        } else {
            Log.d(LOG_TAG, "could not find a network interface");
        }
    } catch (Throwable e) {
        Log.e(LOG_TAG, "vlcTranscode: " + file, e);
    }
}