直接上代码:
创新互联主营秦淮网站建设的网络公司,主营网站建设方案,app软件定制开发,秦淮h5小程序开发搭建,秦淮网站营销推广欢迎秦淮等地区企业咨询
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PortScanner extends Thread {
private int[] p;
Socket ss = null;
public PortScanner(int[] p) {
this.p = p;
}
public static void main(String[] args) {
for (int i = 0; i 65535; i = i + 100) {
new PortScanner(new int[] { i + 1, i + 100 }).start();
}
}
@Override
public void run() {
for (int i = p[0]; i p[1]; i++) {
try {
ss = new Socket("8.8.8.8", i);
System.out.println("扫描到端口: " + i);
} catch (Exception e) {
// System.out.println("关闭端口: " + i);
}
}
}
}
很简单,给你写个例子:
//检测端口8080到8090哪些可用哪些不可用
for(int i = 8080; i8090; i++){
try {
ServerSocket sskt = new ServerSocket(i);
System.out.println("端口[" +i + "]可用。");
} catch (IOException e) {
System.out.println("端口 [" + i + "] 被占用.");
}
}
不要用new InetSocketAddress(host, port));,直接使用new InetSocketAddress( port));,主机用绑定所有
你用0.0.0.0或者127.0.0.1都不对的
使用jpcap,java的截包工具。可以截取主机上某个端口的数据包。在主机上安装邮件服务器,然后监听截取25端口数据并解析,提取有用数据。
Socket
client
=
null;
try{
client
=
new
Socket(IP,
port);
System.out.println("端口已开放");
client.close();
}catch(Exception
e){
System.out.println("端口未开放");
}
====================================================
这样就能正常捕获这个异常,不会阻止程序正常运行!
public class TestPort
{
public static void main(String[] args)
{
System.out.println(getPID("3306"));//得到进程ID,3306是端口名称
System.out.println(getProgramName(getPID("3306")));//根据进程ID得到映像名称
killTask(getProgramName(getPID("3306")));//根据映像名称关闭进程
}
// 得到进程ID
public static String getPID(String port){
InputStream is = null;
BufferedReader br = null;
String pid = null;
try
{
String[] args = new String[]{"cmd.exe","/c","netstat -aon|findstr",port};
is = Runtime.getRuntime().exec(args).getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String temp = br.readLine();
if(temp != null){
String[] strs = temp.split("\\s");
pid=strs[strs.length-1];
}
}
catch (IOException e)
{
e.printStackTrace();
}finally{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return pid;
}
//根据进程ID得到映像名称
public static String getProgramName(String pid){
InputStream is = null;
BufferedReader br = null;
String programName = null;
try
{
String[] args = new String[]{"cmd.exe","/c","tasklist|findstr",pid};
is = Runtime.getRuntime().exec(args).getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String temp = br.readLine();
if(temp != null){
String[] strs = temp.split("\\s");
programName=strs[0];
}
}
catch (IOException e)
{
e.printStackTrace();
}finally{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return programName;
}
//根据映像名称关闭进程
public static void killTask(String programName){
String[] args = new String[]{"Taskkill","/f","/IM",programName};
try
{
Runtime.getRuntime().exec(args);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//题主自己看看具体怎么get它的ip地址,好久没有写,不知道了
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款