Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(CMAccount.SETTINGS_PREFERENCES,
            Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {/*  w  ww  .j a va 2  s.  co  m*/
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (CMAccount.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}

From source file:eu.stratosphere.pact.test.util.minicluster.NepheleMiniCluster.java

private static NetworkInterface getNetworkInterface() throws SocketException {
    final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        if (!nic.isLoopback() && !nic.isPointToPoint())
            return nic;
    }// www. j  a v  a2s . c  o m

    throw new SocketException("Cannot find network interface which is not a loopback interface.");
}

From source file:sce.RESTJobThread.java

public void sendEmail(JobExecutionContext context, String email) {
    try {/* www  .j  a  v  a2s  .  co m*/
        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:sce.ElasticJob.java

public void sendEmail(JobExecutionContext context, String email) throws JobExecutionException {
    try {/*from  w ww.  j  a  v a 2  s  . c o  m*/
        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) {
            throw new JobExecutionException(e);
        }
        //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) {
        throw new JobExecutionException(e);
    }
}

From source file:com.phonemetra.account.util.AccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(Account.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {//ww w. ja  v  a  2s  . c o m
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (Account.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}

From source file:com.poinsart.votar.VotarMain.java

public String getWifiIp() {
    Enumeration<NetworkInterface> en = null;
    try {/*w ww  .j  ava2s.  c  o  m*/
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }
    while (en.hasMoreElements()) {
        NetworkInterface intf = en.nextElement();
        if (intf.getName().contains("wlan")) {
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                    //Log.d("VotAR Main", inetAddress.getHostAddress());
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    }
    return null;
}

From source file:nu.nethome.home.items.net.H2DatabaseTCPServer.java

public String getExternalIPAddress() {
    String result = null;//from w w w  .j a v a2s.c  o m
    Enumeration<NetworkInterface> interfaces2 = null;
    try {
        interfaces2 = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.severe("Can't get network interfaces: " + e.getMessage());
        return "";
    }
    if (interfaces2 != null) {
        while (interfaces2.hasMoreElements() && StringUtils.isEmpty(result)) {
            NetworkInterface i = interfaces2.nextElement();
            Enumeration<InetAddress> addresses2 = i.getInetAddresses();
            while (addresses2.hasMoreElements() && (result == null || result.isEmpty())) {
                InetAddress address = addresses2.nextElement();
                if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) {
                    result = address.getHostAddress();
                }
            }
        }
    }
    return result;
}

From source file:com.elixsr.portforwarder.forwarding.ForwardingService.java

private InetSocketAddress generateFromIpUsingInterface(String interfaceName, int port)
        throws SocketException, ObjectNotFoundException {

    String address = null;/* w w w  . j  a v a 2 s. c  o  m*/
    InetSocketAddress inetSocketAddress;

    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();

        Log.d(TAG, intf.getDisplayName() + " vs " + interfaceName);
        if (intf.getDisplayName().equals(interfaceName)) {

            Log.i(TAG, "Found the relevant Interface. Will attempt to fetch IP Address");

            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

                InetAddress inetAddress = enumIpAddr.nextElement();

                address = new String(inetAddress.getHostAddress().toString());

                if (address != null & address.length() > 0 && inetAddress instanceof Inet4Address) {

                    inetSocketAddress = new InetSocketAddress(address, port);
                    return inetSocketAddress;
                }
            }
        }
    }

    //Failed to find the relevant interface
    //TODO: complete
    //        Toast.makeText(this, "Could not find relevant network interface.",
    //                Toast.LENGTH_LONG).show();
    throw new ObjectNotFoundException("Could not find IP Address for Interface " + interfaceName);
}

From source file:org.apache.synapse.transport.passthru.util.PassThroughTransportUtils.java

/**
 * Whatever this method returns as the IP is ignored by the actual http/s listener when
 * its getServiceEPR is invoked. This was originally copied from axis2
 *
 * @return Returns String./*w  ww  .ja v  a2  s . c  o m*/
 * @throws java.net.SocketException if the socket can not be accessed
 */
public static String getIpAddress() throws SocketException {
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    String address = "127.0.0.1";

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        Enumeration addresses = netface.getInetAddresses();

        while (addresses.hasMoreElements()) {
            InetAddress ip = (InetAddress) addresses.nextElement();
            if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) {
                return ip.getHostAddress();
            }
        }
    }
    return address;
}

From source file:com.petalmd.armor.AbstractUnitTest.java

public static String getNonLocalhostAddress() {
    try {//from w  w w .  j av  a  2  s. c  o m
        for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            final NetworkInterface intf = en.nextElement();

            if (intf.isLoopback() || !intf.isUp()) {
                continue;
            }

            for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                    .hasMoreElements();) {

                final InetAddress ia = enumIpAddr.nextElement();

                if (ia.isLoopbackAddress() || ia instanceof Inet6Address) {
                    continue;
                }

                return ia.getHostAddress();
            }
        }
    } catch (final SocketException e) {
        throw new RuntimeException(e);

    }

    System.out.println("ERROR: No non-localhost address available, will use localhost");
    return "localhost";
}