import java.net.*; import java.io.*; public class lowportscanner { public static void main(string[]...
TRANSCRIPT
import java.net.*;import java.io.*;
public class LowPortScanner {
public static void main(String[] args) { String host = "localhost";
if (args.length > 0) { host = args[0]; } for (int i = 1; i < 1024; i++) { try { Socket s = new Socket(host, i); System.out.println("There is a server on port " + i + " of " + host); } catch (UnknownHostException ex) { System.err.println(ex); break; } catch (IOException ex) { // must not be a server on this port } } // end for } // end main } // end PortScanner
import java.net.*;import java.io.*;
public class SocketInfo {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) { try { Socket theSocket = new Socket(args[i], 80); System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress()); } // end try catch (UnknownHostException ex) { System.err.println("I can't find " + args[i]); } catch (SocketException ex) { System.err.println("Could not connect to " + args[i]); } catch (IOException ex) { System.err.println(ex); }
} // end for
} // end main
} // end SocketInfo
Multicast Sockets
• MulticastSocket: This kind of socket is used on the client-side to listen for packets that the server broadcasts to multiple clients.
import java.io.*; public class MulticastServer { public static void main(String[] args) throws IOException { new MulticastServerThread().start(); }
}
import java.io.*; import java.net.*; import java.util.*; public class MulticastServerThread extends QuoteServerThread { private long FIVE_SECONDS = 5000; public MulticastServerThread() throws IOException { super("MulticastServerThread" ); } public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // construct quote String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); // send it InetAddress group = InetAddress.getByName( "230.0.0.1"); DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446); socket.send(packet); // sleep for a while try { sleep(( long)(Math.random() * FIVE_SECONDS)); } catch (InterruptedException e) { } } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } socket.close(); } }
MulticastSocket socket = new MulticastSocket(4446); InetAddress group = InetAddress.getByName("230.0.0.1"); socket.joinGroup(group); DatagramPacket packet; for (int i = 0; i < 5; i++) { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received); } socket.leaveGroup(group); socket.close();
InetAddress Class
• Represents an IP address• Can convert domain name to IP
address– Performs DNS lookup
• Getting an InetAddress object– getLocalHost()– getByName(String host)– getByAddress(byte[] addr)
InetAddress is a factory
• You can’t create InetAddress objects by invoking the InetAddress constructor
• Instead, invoke static methods of the InetAddress class
• These methods return either a Inet4Address or a Inet6Address– both of which extend InetAddress
• The factory design pattern delegates responsibility for what class of object to create to the factory
import java.net.*;
public class OReillyByName {
public static void main (String[] args) {
try { InetAddress address =
InetAddress.getByName("www.oreilly.com"); System.out.println(address); } catch (UnknownHostException ex) { System.out.println("Could not find www.oreilly.com"); }
}
}
import java.net.*;
public class AllAddressesOfMicrosoft {
public static void main (String[] args) {
try { InetAddress[] addresses = InetAddress.getAllByName("www.microsoft.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException ex) { System.out.println("Could not find www.microsoft.com"); }
}
}
import java.net.*;
public class MyAddress {
public static void main(String[] args) {
try { InetAddress me = InetAddress.getLocalHost(); String dottedQuad = me.getHostAddress(); System.out.println("My address is " + dottedQuad); } catch (UnknownHostException ex) { System.out.println("I'm sorry. I don't know my own address."); }
}
}
import java.net.*;
public class IPCharacteristics {
public static void main(String[] args) { try { InetAddress address = InetAddress.getByName(args[0]); if (address.isAnyLocalAddress()) { System.out.println(address + " is a wildcard address."); } if (address.isLoopbackAddress()) { System.out.println(address + " is loopback address."); } if (address.isLinkLocalAddress()) { System.out.println(address + " is a link-local address."); }
else if (address.isSiteLocalAddress()) { System.out.println(address + " is a site-local address."); } else { System.out.println(address + " is a global address."); } if (address.isMulticastAddress()) { if (address.isMCGlobal()) { System.out.println(address + " is a global multicast address."); } else if (address.isMCOrgLocal()) { System.out.println(address + " is an organization wide multicast address."); } else if (address.isMCSiteLocal()) { System.out.println(address + " is a site wide multicast address."); } else if (address.isMCLinkLocal()) { System.out.println(address + " is a subnet wide multicast address."); }
else if (address.isMCNodeLocal()) { System.out.println(address + " is an interface-local multicast address."); } else { System.out.println(address + " is an unknown multicast address type."); } } else { System.out.println(address + " is a unicast address."); } } catch (UnknownHostException ex) { System.err.println("Could not resolve " + args[0]); }
}
}
import java.net.*;
public class IBiblioAliases {
public static void main (String args[]) {
try { InetAddress ibiblio = InetAddress.getByName("www.ibiblio.org"); InetAddress helios = InetAddress.getByName("helios.metalab.unc.edu"); if (ibiblio.equals(helios)) { System.out.println ("www.ibiblio.org is the same as helios.metalab.unc.edu"); } else { System.out.println ("www.ibiblio.org is not the same as helios.metalab.unc.edu"); } } catch (UnknownHostException ex) { System.out.println("Host lookup failed."); } }}
import java.net.*;import java.util.*;
public class InterfaceLister {
public static void main(String[] args) throws Exception { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) interfaces.nextElement(); System.out.println(ni); } }
}
URL Class
• Provides high-level access to network data• Abstracts the notion of a connection• Constructor opens network connection
– To resource named by URL
• final class - Uses protocol handlers (strategy design pattern) with URL context to select
URL Constructors• URL( fullURL )
– URL( "http://www.cs.umd.edu/class/index.html" )
• URL( baseURL, relativeURL )– URL base = new URL("http://www.cs.umd.edu/" );– URL class = new URL( base, "/class/index.html " );
• URL( protocol, baseURL, relativeURL )– URL( "http", www.cs.umd.edu, "/class/index.html" )
• URL( protocol, baseURL, port, relativeURL )– URL( "http", www.cs.umd.edu, 80,"/class/index.html" )
URL Methods
• getProtocol( )• getHost( )• getPort( )• getFile( )• openConnection() returns URLConnection
• URLConnection– getType()– getInputStream()
URL Reader
URLConnection connection = url.openConnection();
System.out.println("Type : " + connection.getContentType());
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
in.close();
System.out.println(inputLine);
•
Manipulating URLs
• URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
• Sample structure of a URL. The resource name part may contain: host name, file name, port number(optional) and reference (optional)
http://java.sun.com
• you can create a URL object in Java from an absolute URL or a relative URL.
• The URL class provides several methods implemented on URL objects. You can get the protocol, host name, port number, and filename from a URL.
Protocol Identifier Resource Name
Example code
import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL("http://java.sun.com:80/docs/books/" + "tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); }}
Output of the above code:
protocol = httphost = java.sun.comfilename = /docs/books/tutorial/index.htmlport = 80ref = DOWNLOADING
Connecting with a URL (1)• openStream(): returns a java.io.InputStream object, from
which you can read easily as reading from an input stream. It may throw an IOExceptionExample codeimport java.net.*;import java.io.*;
public class ReadURL { public static void main(String[] args) throws Exception {
URL osu = new URL("http://www.osu.edu/");BufferedReader in = new BufferedReader(
new InputStreamReader(osu.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
in.close(); }}
This prints out the source code for the webpage www.osu.edu
Connecting with a URL (2)• openConnection(): Returns a URLConnection object that
represents a connection to the remote object referred to by the URL. It may throws an IOException
try { URL osu = new URL("http://www.osu.edu/"); URLConnection osuConnection = osu.openConnection();} catch (MalformedURLException e) { // new URL() failed . . .} catch (IOException e) { . . .}
• The URLConnection class provides many methods to communicate with the URL, such as reading and writing.
private static void testProtocol(String url) { try { URL u = new URL(url); System.out.println(u.getProtocol() + " is supported"); } catch (MalformedURLException ex) { String protocol = url.substring(0, url.indexOf(':')); System.out.println(protocol + " is not supported"); } }
import java.net.*;import java.applet.*;import java.awt.*;
public class RelativeURLTest extends Applet {
public void init () { try { URL base = this.getDocumentBase(); URL relative = new URL(base, "mailinglists.html"); this.setLayout(new GridLayout(2,1)); this.add(new Label(base.toString())); this.add(new Label(relative.toString())); } catch (MalformedURLException ex) { this.add(new Label("This shouldn't happen!")); } }
}