作为 Socket 的服务器端,按照道理,一般是“来者通吃”,不管是谁来访,我都愿意跟你建立连接。但如果我只想跟指定的家伙建立关系呢?
答案就是利用 ServerSocket 的第三个参数:InetAddress bindAddr。
怎么用呢?先来看看源码是怎么写的。
/** * Create a server with the specified port, listen backlog, and * local IP address to bind to. The <i>bindAddr</i> argument * can be used on a multi-homed host for a ServerSocket that * will only accept connect requests to one of its addresses. * If <i>bindAddr</i> is null, it will default accepting * connections on any/all local addresses. * The port must be between 0 and 65535, inclusive. * A port number of {@code 0} means that the port number is * automatically allocated, typically from an ephemeral port range. * This port number can then be retrieved by calling * {@link #getLocalPort getLocalPort}. * * <P>If there is a security manager, this method * calls its {@code checkListen} method * with the {@code port} argument * as its argument to ensure the operation is allowed. * This could result in a SecurityException. * * The {@code backlog} argument is the requested maximum number of * pending connections on the socket. Its exact semantics are implementation * specific. In particular, an implementation may impose a maximum length * or may choose to ignore the parameter altogther. The value provided * should be greater than {@code 0}. If it is less than or equal to * {@code 0}, then an implementation specific default will be used. * <P> * @param port the port number, or {@code 0} to use a port * number that is automatically allocated. * @param backlog requested maximum length of the queue of incoming * connections. * @param bindAddr the local InetAddress the server will bind to * * @throws SecurityException if a security manager exists and * its {@code checkListen} method doesn't allow the operation. * * @throws IOException if an I/O error occurs when opening the socket. * @exception IllegalArgumentException if the port parameter is outside * the specified range of valid port values, which is between * 0 and 65535, inclusive. * * @see SocketOptions * @see SocketImpl * @see SecurityManager#checkListen * @since JDK1.1 */ public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { setImpl(); if (port < 0 || port > 0xFFFF) throw new IllegalArgumentException( "Port value out of range: " + port); if (backlog < 1) backlog = 50; try { bind(new InetSocketAddress(bindAddr, port), backlog); } catch(SecurityException e) { close(); throw e; } catch(IOException e) { close(); throw e; } }
这么一大段,最重要的一句是什么,就是写在注释里面的那几句。大意就是:“bindAddr 这个参数,如果有的话,那么 ServerSOcket 将只会 access 从这个地址发过来的连接请求,如果没有的话,那么它将允许所有地址发过来的请求”。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于