get Local IP Addresses from java.net.NetworkInterface - Android Network

Android examples for Network:IP Address

Description

get Local IP Addresses from java.net.NetworkInterface

Demo Code

/*****************************************************************************
 *  Project: Android IPv6Config/* ww  w. j a v  a  2  s. c o  m*/
 *  Description: Android application to change IPv6 kernel configuration
 *  Author: Ren? Mayrhofer
 *  Copyright: Ren? Mayrhofer, 2011-2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 
 * as published by the Free Software Foundation.
 *****************************************************************************/
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Vector;

public class Main {

  /**
   * This method doesn't work on Android pre-Honeycomb (3.0) systems for getting
   * IPv6 addresses.
   */
  public static Vector<String> getLocalAddresses() {
    Vector<String> addrs = new Vector<String>();
    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();
          if (!inetAddress.isLoopbackAddress()) {
            addrs.add(inetAddress.getHostAddress());
          }

          if (inetAddress instanceof Inet6Address) {
            // log(Level.FINE, "Found IPv6 address: " + inetAddress.getHostAddress());
          }
        }
      }
    } catch (SocketException ex) {
      // log(Level.SEVERE, ex.toString());
    }
    return addrs;
  }
}

Related Tutorials