Android获取本机局域网IP的方法
16lz
2021-01-23
直接贴代码,主要利用正则表达式匹配局域网ip
package com.rongyan.clienttest;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by XRY on 2017/7/30. */public class NetWorkUtil { //匹配C类地址的IP public static final String regexCIp = "^192\\.168\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)$"; //匹配A类地址 public static final String regexAIp = "^10\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)$"; //匹配B类地址 public static final String regexBIp = "^172\\.(1[6-9]|2\\d|3[0-1])\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)\\.(\\d{1}|[1-9]\\d|1\\d{2}|2[0-4]\\d|25\\d)$"; public static String getHostIp() { String hostIp; Pattern ip = Pattern.compile("(" + regexAIp + ")|" + "(" + regexBIp + ")|" + "(" + regexCIp + ")"); Enumeration networkInterfaces = null; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); } InetAddress address; while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); Enumeration inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { address = inetAddresses.nextElement(); String hostAddress = address.getHostAddress(); Matcher matcher = ip.matcher(hostAddress); if (matcher.matches()) { hostIp = hostAddress; return hostIp; } } } return null; }}
更多相关文章
- Android邮件地址正则表达式
- Android: 用jni 获取MAC地址
- Android水面落叶动态壁纸源码及分析 附下载地址
- android 基于百度地图api开发定位以及获取详细地址
- android 设置静态wifi地址
- Android SDK官方下载地址及在线SDK网址
- SDK,NDK,ADT工具下载常用地址