3.Java获得内网网段所有可通信的ip地址
1.实例代码
如果我们想要确定自己所在的局域网的所有用户,我们可以通过这种方式获取:
步骤如下:
首先获取本机地址,截取自己所在的网段
然后调用系统命令 ping ip -w 280 -n 1(其中ip是变量)根据返回的结果来判断ip是否可通行
如果可通信,将其添加到ip列表中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | package InternetCode.Exa3; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 获得内网所有ip地址 */ public class CoreCode { private static volatile int num = 0 ; public static void main(String[] args) throws IOException { List<String> result=getAllIp(); System.out.println(result); } /** * 获得内网所有的可通信的ip地址 * @return * @throws IOException */ public static List<String> getAllIp() throws IOException { InetAddress host=InetAddress.getLocalHost(); String hostAddress=host.getHostAddress(); int pos=hostAddress.lastIndexOf( "." ); //获得本机ip的网段 String bigNet=hostAddress.substring( 0 ,pos+ 1 ); List<String> ips= Collections.synchronizedList( new ArrayList<>()); for ( int i= 0 ;i<= 225 ;i++){ String ip=bigNet+i; new Thread(()->{ try { Process process = Runtime.getRuntime().exec( "ping " +ip+ " -w 280 -n 1" ); InputStream inputStream=process.getInputStream(); InputStreamReader inputStreamReader= new InputStreamReader(inputStream, "GBK" ); BufferedReader bufferedReader= new BufferedReader(inputStreamReader); String line= null ; String isActive= null ; while ((line=bufferedReader.readLine()) != null ) { if (!line.equals( "" )){ isActive=bufferedReader.readLine().substring( 0 , 2 ); break ; } } if (isActive.equals( "来自" )){ ips.add(ip); } } catch (Exception e){ e.printStackTrace(); } num++; }).start(); } while (num!= 225 ) {} return ips; } } |
作者:small-water
出处:https://www.cnblogs.com/small-water/p/17870109.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
分类:
Java动手做一做之网络编程
标签:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)