笨笨
独学而无友,则孤陋而寡闻
1.什么时候在Socket Client端指定connect from参数:
public Socket(String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException

This constructor creates a socket to the specified port on the specified host and tries to connect. It connects to the host and port specified in the first two arguments. It connects from the local network interface and port specified by the last two arguments. The network interface may be either physical (e.g., a different Ethernet card) or virtual (a multihomed host). If 0 is passed for the localPort argument, Java chooses a random available port between 1,024 and 65,535.

One situation where you might want to explicitly choose the local address would be on a router/firewall that uses dual Ethernet ports. Incoming connections would be accepted on one interface, processed, and forwarded to the local network from the other interface. Suppose you were writing a program to periodically dump error logs to a printer or send them over an internal mail server. You'd want to make sure you used the inward-facing network interface instead of the outward-facing network interface. For example,

 1 try {
 2 
 3   InetAddress inward = InetAddress.getByName("router");
 4 
 5   Socket socket = new Socket("mail"25, inward, 0);
 6 
 7   // work with the sockets
 8 
 9 }
10 
11 catch (UnknownHostException ex) {
12 
13   System.err.println(ex);
14 
15 }
16 
17 catch (IOException ex) {
18 
19   System.err.println(ex);
20 
21 }
22 

By passing 0 for the local port number, I say that I don't care which port is used but I do want to use the network interface bound to the local hostname router.

This constructor can throw an IOException for all the usual reasons given in the previous constructors. Furthermore, an UnknownHostException will also be thrown if the remote host cannot be located.

Finally, an IOException (probably a BindException, although again that's just a subclass of IOException and not specifically declared in the throws clause of this method) will be thrown if the socket is unable to bind to the requested local network interface, which tends to limit the portability of applications that use this constructor. You could take deliberate advantage of this to restrict a compiled program to run on only a predetermined host. It would require customizing distributions for each computer and is certainly overkill for cheap products. Furthermore, Java programs are so easy to disassemble, decompile, and reverse engineer that this scheme is far from foolproof. Nonetheless, it might be part of a scheme to enforce a software license.

posted on 2005-12-23 09:58  笨笨  阅读(411)  评论(0编辑  收藏  举报