Skip to content

Instantly share code, notes, and snippets.

@xxnjdlys
Last active August 29, 2015 14:02
Show Gist options
  • Save xxnjdlys/aa46d77ceac35a250f0f to your computer and use it in GitHub Desktop.
Save xxnjdlys/aa46d77ceac35a250f0f to your computer and use it in GitHub Desktop.
Get Current Device Ip.
package com.sadieyu.androidsocketclient;
import org.apache.http.conn.util.InetAddressUtils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
/**
* Created by sadieyu on 14-6-12.
*/
public class Utils {
/**
* Get IP address from first non-localhost interface
* @param ipv4 true=return ipv4, false=return ipv6
* @return address or empty string
*/
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port suffix
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment