Hi
, I started learning JAVA and I made a small code in java to scan the connected hosts in a local network. I wrote only 3 methods for this, the first one scan the entire network looking for live hosts, the second one scan in a range of IPs and the last one, return the hostname for one IP.
LNScannerimport java.io.*;
import java.net.*;
public class LNScanner
{
public static void HostName(String IP)
{
try
{
InetAddress Host = InetAddress.getByName(IP);
System.out.println(Host.getHostName());
System.out.println(Host.getLoopbackAddress());
}
catch(UnknownHostException UHE)
{
System.out.println(UHE.toString());
}
}
public static void ScanAll()
{
int Host = 1, Lives = 0;
while(Host < 256)
{
try
{
InetAddress in;
in = InetAddress.getByName("192.168.1."+Host);
if(in.isReachable(3000))
{
System.out.println("IP: 192.168.1."+Host+" Hostname: "+in.getHostName());
Lives++;
}
}
catch(UnknownHostException UHE)
{
System.out.println(UHE.toString());
}
catch(IOException IO)
{
System.out.println(IO.toString());
}
Host++;
}
System.out.println("Cantidad de Hosts en la red: " +Lives);
}
public static void RangeScan(int Start, int End)
{
int Host = Start, Lives = 0;
while(Host <= End)
{
try
{
InetAddress in;
in = InetAddress.getByName("192.168.1."+Host);
if(in.isReachable(3000))
{
System.out.println("IP: 192.168.1."+Host+" Hostname: "+in.getHostName());
Lives++;
}
}
catch(UnknownHostException UHE)
{
System.out.println(UHE.toString());
}
catch(IOException IO)
{
System.out.println(IO.toString());
}
Host++;
}
System.out.println("Cantidad de Hosts en la red: " +Lives);
}
}
Main
import java.util.*;
class Main
{
public static void main (String[] args)
{
LNScanner Scan = new LNScanner();
Scanner Read = new Scanner(System.in);
System.out.println(" LNScanner");
System.out.println("Select an option");
System.out.println("1.- Scan for live hosts in the local network");
System.out.println("2.- Scan a range, for live hosts in the local network");
System.out.println("3.- Scan IP for know the hostname");
int Op = Read.nextInt();
switch(Op)
{
case 1:
System.out.println("Starting the scan");
Scan.ScanAll();
break;
case 2:
System.out.println("Enter the range of the scan");
System.out.print("Start in 192.168.1.");
int Start = Read.nextInt();
System.out.print("End in 192.168.1.");
int End = Read.nextInt();
System.out.println("Starting the scan");
Scan.RangeScan(Start, End);
break;
case 3:
System.out.println("Enter the IP address:");
String IP = Read.next();
System.out.println("Starting the scan");
Scan.HostName(IP);
break;
default:
System.out.println("Enter a valid option");
break;
}
}
}