您的位置:首页 > 运维架构 > Linux

java检测linux系统中所有端口的ip地址

2016-01-03 23:02 597 查看
boolean globFlag = false;

int tempPort = Integer.valueOf(port);

//获取设备所有网口的ip地址

Enumeration allNetInterfaces = null;

try {

allNetInterfaces = NetworkInterface.getNetworkInterfaces();

} catch (java.net.SocketException e) {

e.printStackTrace();

}

//检测每一个网口上的这个端口是否可以连接上

InetAddress ip = null;

while (allNetInterfaces.hasMoreElements()) {

NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

Enumeration addresses = netInterface.getInetAddresses();

while (addresses.hasMoreElements()){

ip = (InetAddress) addresses.nextElement();

if(ip!=null && ip instanceof Inet4Address){

String ipAddress = ip.getHostAddress();

log.error("ip:-------"+ipAddress);

try{

Socket socket = new Socket(ipAddress,tempPort);

globFlag = true;

}catch (Exception e) {

// TODO: handle exception

}

if(globFlag){

break;

}

}

}

if(globFlag){

break;

}

}

if(globFlag){

response.setContentType("text/json;charset=UTF-8");

response.getWriter().write(

"{\"success\":"

+ false

+ ",\"msg\":\""

+ "该端口已经被占用" + "\"}");

return null;

}

说明:这种用java的方式去检测linux下的端口 的占用情况存在漏洞,原因就是DNS端口53却没有被检测到,

可以使用 netstat -nap|grep 53 命令去查看,会发现该设备上的所有的网口对应的ip上的端口虽然是没有进程在使用的;

但是该端口是不能作为web服务的端口,因为一旦用web使用该端口号,可以查看到web进程是启动起来的,但是DNS端口就被web占用了,

从而形成死锁,无法访问到web服务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: