Java Reference
In-Depth Information
Now we are ready to scan. A
for
loop is used to count from 0 to 255.
// Scan through IP addresses ending in 0 - 255.
for (int i = 0; i <= 255; i++)
{
String address = ip + i;
String title = scanIP(address);
if (title != null)
list.add(address + ":" + title);
}
For each IP address, the
scanIP
function is called. If a valid site exists at that address,
the title (from the HTML) is returned. If no valid site is found, then the value
null
is re-
turned. The
scanIP
function is covered in detail later in this section.
Once the loop completes, we display what sites were found. The code to do this is shown
below:
// Now display the list of sites found.
System.out.println();
System.out.println("Sites found:");
if (list.size() > 0)
{
for (String site : list)
{
System.out.println(site);
}
The user is informed if there are no sites to display.
} else
{
System.out.println("No sites found");
}
As you saw above, for each IP address, the
scanIP
method was called. I will now show
you how the
scanIP
function is constructed.
The
scanIP
function begins by displaying the IP address that is currently being
scanned. The
downloadPage
method is called to retrieve the HTML at the URL formed
from the IP address. The following lines of code do this.
try
{
System.out.println("Scanning: " + ip);
String page = downloadPage(new URL("http://" + ip),1000);