PD: Se que el escaner se puede refactorizar mediante el uso de hilos pero primero me gustaria que funcione, cualquier sugerencia es bienvenida.
Clase Main:
Código:
package javaescanerpuertosredloca;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
RedLocal red = new RedLocal();
List hosts = red.getHosts();
for (Object ip : hosts)
{
System.out.println(ip.toString());
}
}
}
Código:
package javaescanerpuertosredlocal;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class RedLocal
{
private List<Host> hosts;
public RedLocal()
{
this.hosts = new ArrayList<>();
}
public List<Host> getHosts()
{
byte[] ip = {(byte)192, (byte)168, 1, 0}; //Valido para 192.168.1.x
for (int i = 1; i <= 254; i++)
{
try
{
ip[3] = (byte) i;
InetAddress address;
address = InetAddress.getByAddress(ip);
if(address.isReachable(1000))
{
this.hosts.add(new Host(address));
}
}
catch (UnknownHostException ex)
{
}
catch (IOException ex)
{
}
}
return hosts;
}
public void setHosts(List<Host> hosts)
{
this.hosts = hosts;
}
@Override
public String toString()
{
return "RedLocal{" + "hosts=" + hosts + '}';
}
}
Clase Puerto:
Código:
package javaescanerpuertosredloca;
public class Puerto
{
private int puerto;
private Servicio servicio;
public Puerto(int puerto)
{
this.puerto = puerto;
}
public int getPuerto()
{
return puerto;
}
public void setPuerto(int puerto)
{
this.puerto = puerto;
}
@Override
public String toString()
{
return "Puerto{" + "puerto=" + puerto + '}';
}
}
Código:
package javaescanerpuertosredlocal;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Host
{
private List<Puerto> puertos;
private InetAddress ip;
public Host(InetAddress ip)
{
this.puertos = new ArrayList<>();
this.ip = ip;
getPuertos();
}
public List<Puerto> getPuertos()
{
for(int i=0;i<65500;i++)
{
try
{
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, i), 200);
this.puertos.add(new Puerto(i));
socket.close();
}
catch (IOException ex)
{
}
}
return puertos;
}
public void setPuertos(List<Puerto> puertos)
{
this.puertos = puertos;
}
@Override
public String toString()
{
return ip+"{" + "puertos=" + puertos + '}';
}
}
Y faltaria la clase Servicio que no se como hacerla