To prevent these sorts of attacks Java defines a number of different security levels for applets loaded from the Internet. As a general rule applets are only allowed to communicate with the host from which they were downloaded (the code base). They cannot make connections to arbitrary hosts on the Internet. Applications, however, are allowed to connect to arbitrary hosts.
There is some level of user control--some browsers allow the user to prevent an applet from making any network connections or to allow it unrestricted access--but most of the itme this is the case. This is always the case with Netscape.
If you're uncertain of how much network access you'll have, you can use these methods from java.lang.SecurityManager
to check:
public void checkConnect(String host, int port)
public void checkConnect(String host, int port, Object context)
public void checkListen(int port)
public void checkAccept(String hostname, int port)
public void checkMulticast(InetAddress maddr)
public void checkMulticast(InetAddress maddr, byte ttl)
Each of these methods throws a SecurityException
(which is a runtime exception so it doesn't need to be declared) if the requested operation is not permitted. For example, to check whether you're allow to open a socket to port 80 of www.poly.edu you would write:
try {
SecurityManager sm = SecurityManager.getSecurityManager();
if (sm != null) sm.checkConnect("www.poly.edu", 80);
// open the socket...
}
catch (SecurityException e) {
System.err.println("Sorry. I'm not allowed to connect to that host.");
}
checkConnect()
tests whether a socket connection is allowed.
checkListen()
tests whether binding to a particular port
is allowed. checkAccept()
tests whether you can accept a connection from a particular remote host and port. checkMulticast()
tests whether multicasting is allowed.