Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInetAddresses.

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:org.openbaton.nfvo.system.SystemStartup.java

@Override
public void run(String... args) throws Exception {
    log.info("Initializing OpenBaton");

    log.debug(Arrays.asList(args).toString());

    propFileLocation = propFileLocation.replace("file:", "");
    log.debug("Property file: " + propFileLocation);

    InputStream is = new FileInputStream(propFileLocation);
    Properties properties = new Properties();
    properties.load(is);/* w ww  . j ava  2  s .co m*/

    log.debug("Config Values are: " + properties.values());

    Configuration c = new Configuration();

    c.setName("system");
    c.setConfigurationParameters(new HashSet<ConfigurationParameter>());

    /**
     * Adding properties from file
     */
    for (Entry<Object, Object> entry : properties.entrySet()) {
        ConfigurationParameter cp = new ConfigurationParameter();
        cp.setConfKey((String) entry.getKey());
        cp.setValue((String) entry.getValue());
        c.getConfigurationParameters().add(cp);
    }

    /**
     * Adding system properties
     */
    Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netint : Collections.list(nets)) {
        ConfigurationParameter cp = new ConfigurationParameter();
        log.trace("Display name: " + netint.getDisplayName());
        log.trace("Name: " + netint.getName());
        cp.setConfKey("ip-" + netint.getName().replaceAll("\\s", ""));
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            if (inetAddress.getHostAddress().contains(".")) {
                log.trace("InetAddress: " + inetAddress.getHostAddress());
                cp.setValue(inetAddress.getHostAddress());
            }
        }
        log.trace("");
        c.getConfigurationParameters().add(cp);
    }

    configurationRepository.save(c);

    if (installPlugin) {
        startPlugins(pluginDir);
    }
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public String getLocalIpAddress() {
    try {/*from  w w w . j a va2s.c  o  m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("", ex.toString());
    }
    return null;
}

From source file:sce.RESTJobThread.java

public void sendEmail(JobExecutionContext context, String email) {
    try {// w w  w .  j  a v a2  s . c om
        Date d = new Date();
        String message = "Job was executed at: " + d.toString() + "\n";
        SchedulerMetaData schedulerMetadata = context.getScheduler().getMetaData();
        //Get the scheduler instance id
        message += "Scheduler Instance Id: " + schedulerMetadata.getSchedulerInstanceId() + "\n";
        //Get the scheduler name
        message += "Scheduler Name: " + schedulerMetadata.getSchedulerName() + "\n";
        try {
            //Get the scheduler ip
            Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
            message += "Scheduler IP: ";
            for (; n.hasMoreElements();) {
                NetworkInterface e = n.nextElement();
                //System.out.println("Interface: " + e.getName());
                Enumeration<InetAddress> a = e.getInetAddresses();
                for (; a.hasMoreElements();) {
                    InetAddress addr = a.nextElement();
                    message += !addr.getHostAddress().equals("127.0.0.1") ? addr.getHostAddress() + " " : "";
                }
            }
            message += "\n";
        } catch (SocketException e) {
            //message += "Scheduler IP: " + e.getMessage() + "\n";
        }
        //Returns the result (if any) that the Job set before its execution completed (the type of object set as the result is entirely up to the particular job).
        //The result itself is meaningless to Quartz, but may be informative to JobListeners or TriggerListeners that are watching the job's execution. 
        message += "Result: "
                + (context.getResult() != null ? truncateResult((String) context.getResult()) : "") + "\n";
        //Get the unique Id that identifies this particular firing instance of the trigger that triggered this job execution. It is unique to this JobExecutionContext instance as well. 
        message += "Fire Instance Id: "
                + (context.getFireInstanceId() != null ? context.getFireInstanceId() : "") + "\n";
        //Get a handle to the Calendar referenced by the Trigger instance that fired the Job. 
        message += "Calendar: " + (context.getCalendar() != null ? context.getCalendar().getDescription() : "")
                + "\n";
        //The actual time the trigger fired. For instance the scheduled time may have been 10:00:00 but the actual fire time may have been 10:00:03 if the scheduler was too busy. 
        message += "Fire Time: " + (context.getFireTime() != null ? context.getFireTime() : "") + "\n";
        //the job name
        message += "Job Name: "
                + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getName() : "")
                + "\n";
        //the job group
        message += "Job Group: "
                + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getGroup() : "")
                + "\n";
        //The amount of time the job ran for (in milliseconds). The returned value will be -1 until the job has actually completed (or thrown an exception), and is therefore generally only useful to JobListeners and TriggerListeners.
        //message += "RunTime: " + context.getJobRunTime() + "\n";
        //the next fire time
        message += "Next Fire Time: "
                + (context.getNextFireTime() != null && context.getNextFireTime().toString() != null
                        ? context.getNextFireTime().toString()
                        : "")
                + "\n";
        //the previous fire time
        message += "Previous Fire Time: "
                + (context.getPreviousFireTime() != null && context.getPreviousFireTime().toString() != null
                        ? context.getPreviousFireTime().toString()
                        : "")
                + "\n";
        //refire count
        message += "Refire Count: " + context.getRefireCount() + "\n";

        //job data map
        message += "\nJob data map: \n";
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) {
            message += entry.getKey() + " = " + entry.getValue() + "\n";
        }
        Mail.sendMail("SCE notification", message, email, null, null);
    } catch (SchedulerException e) {
    }
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

@SuppressWarnings("unchecked")
private void addIps(JSONObject values) {
    List<String> ip4s = new ArrayList<>();
    List<String> ip6s = new ArrayList<>();
    String ip = "unknown";
    try {/*from   ww  w .j a  va 2s . c o  m*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress address = inetAddresses.nextElement();
                if (address instanceof Inet4Address) {
                    ip4s.add(address.getHostAddress() + "_" + address.getHostName());
                    if (!address.isLinkLocalAddress() && !address.isAnyLocalAddress()
                            && !address.isLoopbackAddress()) {
                        ip = address.getHostAddress();
                    }
                }
                if (address instanceof Inet6Address) {
                    ip6s.add(address.getHostAddress() + "_" + address.getHostName());
                }
            }
        }
        ip4s.add("LOC_" + InetAddress.getLocalHost().getHostAddress() + "_"
                + InetAddress.getLocalHost().getHostName());
        if (!ip4s.isEmpty()) {
            values.put("ip", ip);
            values.put("ip4s", ip4s);
        }
        if (!ip6s.isEmpty()) {
            values.put("ip6s", ip6s);
        }
    } catch (UnknownHostException | SocketException e) {
        values.put("ip", "offline_" + e.getMessage());
    }
}

From source file:org.apache.nifi.processors.standard.ListenTCPRecord.java

@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    this.port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();

    final int readTimeout = context.getProperty(READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int maxSocketBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B)
            .intValue();/*from  w w  w  .  j  av  a 2s  .  c o m*/
    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER)
            .asControllerService(RecordReaderFactory.class);

    // if the Network Interface Property wasn't provided then a null InetAddress will indicate to bind to all interfaces
    final InetAddress nicAddress;
    final String nicAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions()
            .getValue();
    if (!StringUtils.isEmpty(nicAddressStr)) {
        NetworkInterface netIF = NetworkInterface.getByName(nicAddressStr);
        nicAddress = netIF.getInetAddresses().nextElement();
    } else {
        nicAddress = null;
    }

    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    // create a ServerSocketChannel in non-blocking mode and bind to the given address and port
    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(nicAddress, port));

    this.dispatcher = new SocketChannelRecordReaderDispatcher(serverSocketChannel, sslContext, clientAuth,
            readTimeout, maxSocketBufferSize, maxConnections, recordReaderFactory, socketReaders, getLogger());

    // start a thread to run the dispatcher
    final Thread readerThread = new Thread(dispatcher);
    readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]");
    readerThread.setDaemon(true);
    readerThread.start();
}

From source file:org.alfresco.bm.test.Test.java

/**
 * Initialize IP address and hostname/*  w  w  w  .j av a 2 s  .  c  om*/
 */
private void initNetworkDetails() throws Exception {
    // We have some preferences about what to use
    InetAddress ipv4 = null;
    InetAddress multicast = null;
    InetAddress ipv6 = null;

    // Get an IP address and host name
    Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    while (nis.hasMoreElements()) {
        NetworkInterface ni = nis.nextElement();
        // Check each network interface
        Enumeration<InetAddress> ias = ni.getInetAddresses();
        while (ias.hasMoreElements()) {
            InetAddress ia = ias.nextElement();
            if (ipv4 == null && ia instanceof Inet4Address) {
                // Our first choice
                ipv4 = ia;
            } else if (multicast != null && ia.isMulticastAddress()) {
                multicast = ia;
            } else if (ipv6 != null && ia instanceof Inet6Address) {
                ipv6 = ia;
            }
        }
    }
    // Now go by preference
    if (ipv4 != null) {
        inetAddress = ipv4;
    } else if (multicast != null) {
        inetAddress = multicast;
    } else if (ipv6 != null) {
        inetAddress = ipv6;
    } else if (inetAddress == null) {
        inetAddress = InetAddress.getLocalHost();
    }
}

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Tell controller that we're ready to handle channels.
 *///from  w  w w  . ja v  a  2 s  .  c  om
public void run() {
    try {
        //get the configuration from json file
        List<OSPFArea> areas = getConfiguration();
        //get the connected interfaces
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        // Check NetworkInterfaces and area-config have same IP Address
        for (NetworkInterface netInt : Collections.list(nets)) {
            // if the interface is up & not loopback
            if (!netInt.isUp() && !netInt.isLoopback()) {
                continue;
            }
            //get all the InetAddresses
            Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                String ipAddress = inetAddress.getHostAddress();
                //Search for the address in all configured areas interfaces
                for (OSPFArea area : areas) {
                    for (OSPFInterface ospfIf : area.getInterfacesLst()) {
                        String ipFromConfig = ospfIf.getIpAddress();
                        if (ipFromConfig.trim().equals(ipAddress.trim())) {
                            log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress,
                                    area.getAreaID());
                            // if same IP address create
                            try {
                                log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort);

                                final ServerBootstrap bootstrap = createServerBootStrap();
                                bootstrap.setOption("reuseAddr", true);
                                bootstrap.setOption("child.keepAlive", true);
                                bootstrap.setOption("child.tcpNoDelay", true);
                                bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);

                                //Set the interface name in ospfInterface
                                ospfIf.setInterfaceName(netInt.getDisplayName());
                                //netInt.get
                                // passing OSPFArea and interface to pipelinefactory
                                ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area,
                                        ospfIf);
                                bootstrap.setPipelineFactory(pfact);
                                InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress),
                                        ospfPort);

                                cg = new DefaultChannelGroup();
                                cg.add(bootstrap.bind(sa));

                                log.debug("Listening for connections on {}", sa);
                                //For testing. remove this
                                interfc = ospfIf;

                                //Start aging process
                                area.initializeDB();
                                area.initializeArea();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("Error::Controller:: {}", e.getMessage());
    }
}

From source file:com.cubic9.android.droidglove.Main.java

/**
 * get IP Address of phone//from  w  w w.  ja  v  a2 s.  c om
 * @return IP address String or error message
 */
private String getIPAddress() {
    Enumeration<NetworkInterface> interfaces = null;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        new AlertDialog.Builder(Main.this).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(getString(R.string.dialog_error_title))
                .setMessage(getString(R.string.dialog_error_get_ip))
                .setPositiveButton(R.string.dialog_error_ok, null).create().show();
        e.printStackTrace();
    }

    while (interfaces.hasMoreElements()) {
        NetworkInterface network = interfaces.nextElement();
        Enumeration<InetAddress> addresses = network.getInetAddresses();

        while (addresses.hasMoreElements()) {
            String address = addresses.nextElement().getHostAddress();

            // If found not 127.0.0.1 and not 0.0.0.0, return it
            if (!"127.0.0.1".equals(address) && !"0.0.0.0".equals(address)
                    && InetAddressUtils.isIPv4Address(address)) {
                return address;
            }
        }
    }

    return "An error occured while getting IP address.";
}

From source file:com.terminal.ide.TermService.java

public String getLocalIpAddress() {
    String addr = null;//from  w w w  .  jav a2 s.com

    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                String ip = inetAddress.getHostAddress().toString();
                if (!inetAddress.isLoopbackAddress()) {
                    if (addr == null || ip.length() < addr.length()) {
                        addr = ip;
                    }
                }
            }
        }

    } catch (SocketException ex) {
        Log.e("SpartacusRex GET LOCAL IP : ", ex.toString());
    }

    if (addr != null) {
        return addr;
    }

    return "127.0.0.1";
}