@Override
  public DatagramChannel bind(SocketAddress local) throws IOException {
    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          ensureOpen();
          if (localAddress != null) throw new AlreadyBoundException();
          InetSocketAddress isa;
          if (local == null) {
            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0);
            } else {
              isa = new InetSocketAddress(0);
            }
          } else {
            isa = Net.checkAddress(local);

            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              InetAddress addr = isa.getAddress();
              if (!(addr instanceof Inet4Address)) throw new UnsupportedAddressTypeException();
            }
          }
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) {
            sm.checkListen(isa.getPort());
          }
          Net.bind(family, fd, isa.getAddress(), isa.getPort());
          localAddress = Net.localAddress(fd);
        }
      }
    }
    return this;
  }
示例#2
0
 /**
  * Binds this DatagramSocket to a specific address & port.
  *
  * <p>If the address is <code>null</code>, then the system will pick up an ephemeral port and a
  * valid local address to bind the socket.
  *
  * <p>
  *
  * @param addr The address & port to bind to.
  * @throws SocketException if any error happens during the bind, or if the socket is already
  *     bound.
  * @throws SecurityException if a security manager exists and its <code>checkListen</code> method
  *     doesn't allow the operation.
  * @throws IllegalArgumentException if addr is a SocketAddress subclass not supported by this
  *     socket.
  * @since 1.4
  */
 public synchronized void bind(SocketAddress addr) throws SocketException {
   if (isClosed()) throw new SocketException("Socket is closed");
   if (isBound()) throw new SocketException("already bound");
   if (addr == null) addr = new InetSocketAddress(0);
   if (!(addr instanceof InetSocketAddress))
     throw new IllegalArgumentException("Unsupported address type!");
   InetSocketAddress epoint = (InetSocketAddress) addr;
   if (epoint.isUnresolved()) throw new SocketException("Unresolved address");
   SecurityManager sec = System.getSecurityManager();
   if (sec != null) {
     sec.checkListen(epoint.getPort());
   }
   try {
     getImpl().bind(epoint.getPort(), epoint.getAddress());
   } catch (SocketException e) {
     getImpl().close();
     throw e;
   }
   bound = true;
 }
 @Override
 public void checkListen(final int pPort) {
   if (finalSecurityManager != null) finalSecurityManager.checkListen(pPort);
 }
 @Override
 public void checkListen(final int port) {
   if (securityManager != null) securityManager.checkListen(port);
 }