用Java写一个网页显示当前局域网的所有ip地址
时间: 2023-11-04 15:04:24 浏览: 99
获取局域网中所有IP地址
4星 · 用户满意度95%
您好,以下是一个简单的Java代码,可以获取当前局域网内的所有IP地址并在网页上显示出来:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class LanIPScanner {
public static void main(String[] args) {
List<String> ipList = new ArrayList<>();
try {
String subnet = "192.168.1.";
for (int i = 1; i < 255; i++) {
String host = subnet + i;
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isReachable(100)) {
ipList.add(host);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(ipList);
}
}
```
这段代码将扫描局域网中的IP地址,从192.168.1.1到192.168.1.254,检查每个主机是否可达,并将可达的IP地址添加到一个列表中。您可以将这个列表在网页上显示出来,如下所示:
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LanIPScannerServlet")
public class LanIPScannerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LanIPScannerServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
List<String> ipList = new ArrayList<>();
try {
String subnet = "192.168.1.";
for (int i = 1; i < 255; i++) {
String host = subnet + i;
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isReachable(100)) {
ipList.add(host);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
out.println("<html>");
out.println("<head><title>Lan IP Scanner</title></head>");
out.println("<body>");
out.println("<h1>局域网IP地址列表</h1>");
out.println("<ul>");
for (String ip : ipList) {
out.println("<li>" + ip + "</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
这个Servlet将扫描局域网中的IP地址,并将它们显示在一个HTML页面中。您可以使用任何Web服务器(如Tomcat)来运行这个Servlet。
阅读全文