是否可以使用一些代码获得设备的IP地址?
当前回答
这是这个答案的返工,去掉了不相关的信息,添加了有用的评论,更清楚地命名变量,并改进了逻辑。
不要忘记包含以下权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
InternetHelper.java:
public class InternetHelper {
/**
* Get IP address from first non-localhost interface
*
* @param useIPv4 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 interface_ : interfaces) {
for (InetAddress inetAddress :
Collections.list(interface_.getInetAddresses())) {
/* a loopback address would be something like 127.0.0.1 (the device
itself). we want to return the first non-loopback address. */
if (!inetAddress.isLoopbackAddress()) {
String ipAddr = inetAddress.getHostAddress();
boolean isIPv4 = ipAddr.indexOf(':') < 0;
if (isIPv4 && !useIPv4) {
continue;
}
if (useIPv4 && !isIPv4) {
int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
ipAddr = delim < 0 ? ipAddr.toUpperCase() :
ipAddr.substring(0, delim).toUpperCase();
}
return ipAddr;
}
}
}
} catch (Exception ignored) { } // if we can't connect, just return empty string
return "";
}
/**
* Get IPv4 address from first non-localhost interface
*
* @return address or empty string
*/
public static String getIPAddress() {
return getIPAddress(true);
}
}
其他回答
下面的代码可能会帮助你..不要忘记添加权限..
public String getLocalIpAddress(){
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()) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
在清单文件中添加以下权限。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
编码快乐! !
kotlin语言。
fun contextIP(context: Context): String {
val wm: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
return Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
}
private InetAddress getLocalAddress()throws IOException {
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()) {
//return inetAddress.getHostAddress().toString();
return inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return null;
}
这里是@Nilesh和@anargund的kotlin版本
fun getIpAddress(): String {
var ip = ""
try {
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
ip = Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
} catch (e: java.lang.Exception) {
}
if (ip.isEmpty()) {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val networkInterface = en.nextElement()
val enumIpAddr = networkInterface.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
val host = inetAddress.getHostAddress()
if (host.isNotEmpty()) {
ip = host
break;
}
}
}
}
} catch (e: java.lang.Exception) {
}
}
if (ip.isEmpty())
ip = "127.0.0.1"
return ip
}
public static String getdeviceIpAddress() {
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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?