局域网IP扫描器
局域网IP扫描器(简单多线程版)
起因:树莓派烧录系统之后没有显示器,想查找出来同一局域网下的IP
一、获取本机IP
InetAddress host = null;
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("本机网段获取失败");
}
二、截取拼接本机网段
String hostAddress = host.getHostAddress();
System.out.println("本机ip为:" + hostAddress);
String[] split = hostAddress.split("\\.");
String segment = split[0] + "." + split[1] + "." + split[2] + ".";
三、构造ping方法
class pingIP {
public void ping(String ip){
try {
// 模拟cmd
Process p = Runtime.getRuntime().exec("ping " + ip);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
while (br.readLine() != null){
// 如果包含TTL就是成功
if (br.readLine().contains("TTL")){
System.out.println(ip);
sb.append(ip);
}else if (br.readLine().contains("无法访问")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("ping方法IO异常");
}catch (NullPointerException e){
e.printStackTrace();
System.out.println("ping方法空指针异常");
}
}
}
四、重写run方法
public void run() {
pingIP pingIP = new pingIP();
pingIP.ping(ip);
}
五、遍历
for (int i = 0; i < 255; i++) {
sniffer ss = new sniffer(segment + i);
new Thread(ss).start();
}
完整项目代码
package TestBasis.lanSniffing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* @ClassName: sniffer
* @Description:
* @Author: 无心
* @Date: 2021-02-09 14:24
* @Version: 1.0
**/
public class sniffer implements Runnable{
private StringBuffer sb = new StringBuffer();
private String ip;
public sniffer(String ip) {
this.ip = ip;
}
public void run() {
pingIP pingIP = new pingIP();
pingIP.ping(ip);
}
public static void main(String[] args) {
System.out.println("获取本机网段中...");
InetAddress host = null;
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("本机网段获取失败");
}
String hostAddress = host.getHostAddress();
System.out.println("本机ip为:" + hostAddress);
String[] split = hostAddress.split("\\.");
String segment = split[0] + "." + split[1] + "." + split[2] + ".";
System.out.println("局域网设备扫描器开始运行,以下ip皆为局域网设备:");
for (int i = 0; i < 255; i++) {
sniffer ss = new sniffer(segment + i);
new Thread(ss).start();
}
}
class pingIP {
public void ping(String ip){
try {
// 模拟cmd的ping
Process p = Runtime.getRuntime().exec("ping " + ip);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
while (br.readLine() != null){
// 如果包含TTL就是成功
if (br.readLine().contains("TTL")){
System.out.println(ip);
sb.append(ip);
}else if (br.readLine().contains("无法访问")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("ping方法IO异常");
}catch (NullPointerException e){
e.printStackTrace();
System.out.println("ping方法空指针异常");
}
}
}
}
苟利国家生死以,岂因祸福避趋之