Android获取本机局域网IP的方法
16lz
2022-04-03
直接贴代码,主要利用正则表达式匹配局域网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(安卓)Studio类库
- Android邮件地址正则表达式
- 在服务器上使用grandle打包android源码
- Android之百度地图开发,包含定位,覆盖物,经纬度位置转换,长按设置中
- android中如何获取视频时长
- android图片下载工具类
- Android:JNI Local Reference Changes in ICS
- Android学习笔记——蓝牙入门
- 优秀的android开源项目