get Wifi NetworkInterface - Android android.net.wifi

Android examples for android.net.wifi:Wifi Property

Description

get Wifi NetworkInterface

Demo Code

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Locale;

import android.util.Log;

public class Main {
  private static final String TAG = "wifi-utils";

  public static NetworkInterface getWifiInterface() {
    Enumeration<NetworkInterface> nis;
    try {//from ww  w  .j a va 2 s . co m
      nis = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      Log.e(TAG, "getWifiInterface could not getNetworkInterfaces: " + e.getMessage(), e);
      return null;
    }
    LinkedList<NetworkInterface> bestnis = new LinkedList<NetworkInterface>();
    // order best?!
    while (nis.hasMoreElements()) {
      NetworkInterface ni = nis.nextElement();
      String name = ni.getName().toLowerCase(Locale.US);
      if (name.startsWith("lo")) {
        Log.d(TAG, "skip loopback interface " + name);
        continue;
      }
      if (name.startsWith("w"))
        bestnis.addFirst(ni);
      else
        bestnis.addLast(ni);
    }
    for (NetworkInterface ni : bestnis) {
      // IPv4 only for now?!
      Enumeration<InetAddress> ias = ni.getInetAddresses();
      while (ias.hasMoreElements()) {
        InetAddress addr = ias.nextElement();
        if (addr.isLoopbackAddress())
          continue;
        if (addr.isMulticastAddress())
          continue;
        if (addr instanceof Inet4Address) {
          return ni;
        }
      }
    }
    return null;
  }
}

Related Tutorials