java.net.BindException类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.8k)|赞(0)|评价(0)|浏览(280)

本文整理了Java中java.net.BindException类的一些代码示例,展示了BindException类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BindException类的具体详情如下:
包路径:java.net.BindException
类名称:BindException

BindException介绍

[英]A BindException is thrown when a process cannot bind a local address/port, either because it is already bound or reserved by the OS.

Most applications should not catch this exception; it is more robust to catch the superclass SocketException.
[中]当进程无法绑定本地地址/端口时,会引发BindException,原因可能是该地址/端口已被OS绑定或保留。
大多数应用程序不应捕获此异常;捕获超类SocketException更加健壮。

代码示例

代码示例来源:origin: wildfly/wildfly

public static void bind(final ServerSocketChannel ch, InetAddress bind_addr, int start_port, int end_port, int backlog) throws Exception {
  int original_start_port=start_port;
  while(true) {
    try {
      ch.bind(new InetSocketAddress(bind_addr, start_port), backlog);
    }
    catch(SocketException bind_ex) {
      if(start_port == end_port)
        throw new BindException("No available port to bind to in range [" + original_start_port + " .. " + end_port + "]");
      if(bind_addr != null && !bind_addr.isLoopbackAddress()) {
        NetworkInterface nic=NetworkInterface.getByInetAddress(bind_addr);
        if(nic == null)
          throw new BindException("bind_addr " + bind_addr + " is not a valid interface: " + bind_ex);
      }
      start_port++;
      continue;
    }
    break;
  }
}

代码示例来源:origin: apache/flink

if (future.isSuccess()) {
  final InetSocketAddress localAddress = (InetSocketAddress) future.channel().localAddress();
  serverAddress = new InetSocketAddress(localAddress.getAddress(), localAddress.getPort());
  return true;
log.debug("Failed to start {} on port {}: {}.", serverName, port, e.getMessage());
try {

代码示例来源:origin: apache/geode

serverSocket.setReceiveBufferSize(socketBufferSize);
 serverSocket.bind(new InetSocketAddress(bindAddr, nport), backlog);
 finishServerSocket(serverSocket);
 return serverSocket;
} else {
 ServerSocket result = new ServerSocket();
 result.setReuseAddress(true);
  result.setReceiveBufferSize(socketBufferSize);
  result.bind(new InetSocketAddress(bindAddr, nport), backlog);
 } catch (BindException e) {
  BindException throwMe =
    new BindException(String.format("Failed to create server socket on %s[%s]",
      bindAddr == null ? InetAddress.getLocalHost() : bindAddr,
      String.valueOf(nport)));
  throwMe.initCause(e);
  throw throwMe;

代码示例来源:origin: apache/hbase

/**
 * A convenience method to bind to a given address and report
 * better exceptions if the address is not a valid host.
 * @param socket the socket to bind
 * @param address the address to bind to
 * @param backlog the number of connections allowed in the queue
 * @throws BindException if the address can't be bound
 * @throws UnknownHostException if the address isn't a valid host name
 * @throws IOException other random errors from bind
 */
public static void bind(ServerSocket socket, InetSocketAddress address,
            int backlog) throws IOException {
 try {
  socket.bind(address, backlog);
 } catch (BindException e) {
  BindException bindException =
   new BindException("Problem binding to " + address + " : " +
     e.getMessage());
  bindException.initCause(e);
  throw bindException;
 } catch (SocketException e) {
  // If they try to bind to a different host's address, give a better
  // error message.
  if ("Unresolved address".equals(e.getMessage())) {
   throw new UnknownHostException("Invalid hostname for server: " +
                   address.getHostName());
  }
  throw e;
 }
}

代码示例来源:origin: apache/hbase

protected RpcServerInterface createRpcServer(Server server, Configuration conf,
  RpcSchedulerFactory rpcSchedulerFactory, InetSocketAddress bindAddress, String name)
  throws IOException {
 boolean reservoirEnabled = conf.getBoolean(RESERVOIR_ENABLED_KEY, true);
 try {
  return RpcServerFactory.createRpcServer(server, name, getServices(),
    bindAddress, // use final bindAddress for this server.
    conf, rpcSchedulerFactory.create(conf, this, server), reservoirEnabled);
 } catch (BindException be) {
  throw new IOException(be.getMessage() + ". To switch ports use the '"
    + HConstants.REGIONSERVER_PORT + "' configuration property.",
    be.getCause() != null ? be.getCause() : be);
 }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * @param port
 *      Use 0 to choose a random port.
 */
public TcpSlaveAgentListener(int port) throws IOException {
  super("TCP agent listener port="+port);
  try {
    serverSocket = ServerSocketChannel.open();
    serverSocket.socket().bind(new InetSocketAddress(port));
  } catch (BindException e) {
    throw (BindException)new BindException("Failed to listen on port "+port+" because it's already in use.").initCause(e);
  }
  this.configuredPort = port;
  setUncaughtExceptionHandler((t, e) -> {
    LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener " + t + ", attempting to reschedule thread", e);
    shutdown();
    TcpSlaveAgentListenerRescheduler.schedule(t, e);
  });
  LOGGER.log(Level.FINE, "TCP agent listener started on port {0}", getPort());
  start();
}

代码示例来源:origin: org.jgroups/com.springsource.org.jgroups

m_serverSocketChannel = ServerSocketChannel.open();
m_serverSocketChannel.configureBlocking(false);
while (true)
   if (bind_addr == null)
     sockAddr=new InetSocketAddress(start_port);
     m_serverSocketChannel.socket().bind(sockAddr);
     sockAddr=new InetSocketAddress(bind_addr, start_port);
     m_serverSocketChannel.socket().bind(sockAddr, backlog);
     throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
   start_port++;
   continue;
     throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
   start_port++;
   continue;

代码示例来源:origin: org.apache.hadoop/hadoop-common

range = conf.getRange(rangeConf, "");
if (range == null || range.isEmpty() || (address.getPort() != 0)) {
 socket.bind(address, backlog);
} else {
 for (Integer port : range) {
  if (socket.isBound()) break;
  try {
   InetSocketAddress temp = new InetSocketAddress(address.getAddress(),
     port);
   socket.bind(temp, backlog);
  } catch(BindException e) {
 if (!socket.isBound()) {
  throw new BindException("Could not find a free port in "+range);

代码示例来源:origin: org.glassfish.external/grizzly-module

serverSocketChannel = ServerSocketChannel.open();
  serverSocket = serverSocketChannel.socket();
  serverSocket.setReuseAddress(reuseAddress);
  if ( inet == null){
    serverSocket.bind(new InetSocketAddress(port),ssBackLog);
  } else {
    serverSocket.bind(new InetSocketAddress(inet,port),ssBackLog);
  serverSocketChannel.configureBlocking(false);
  serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
throw new BindException(ex.getMessage() + ": " + port + "=" + this);

代码示例来源:origin: robovm/robovm

public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException {
  if (address instanceof Inet6Address && ((Inet6Address) address).getScopeId() == 0) {
    // Linux won't let you bind a link-local address without a scope id. Find one.
    NetworkInterface nif = NetworkInterface.getByInetAddress(address);
    if (nif == null) {
      throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
    }
    try {
      address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
    } catch (UnknownHostException ex) {
      throw new AssertionError(ex); // Can't happen.
    }
  }
  try {
    Libcore.os.bind(fd, address, port);
  } catch (ErrnoException errnoException) {
    throw new BindException(errnoException.getMessage(), errnoException);
  }
}

代码示例来源:origin: mil.army.missioncommand/mil-sym-renderer

httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", portNumber), backlog);
} catch(BindException bexc){
      String strTypicalPortInUseMessage = "Address already in use: bind";
      if(bexc.getMessage().startsWith(strTypicalPortInUseMessage))
        System.err.println(bexc.getMessage());
        bexc.printStackTrace();

代码示例来源:origin: commons-net/commons-net

throw new BindException("All ports in use.");
_output_.write(Integer.toString(server.getLocalPort()).getBytes("UTF-8")); // $NON-NLS
_output_.write(NULL_CHAR);
_output_.flush();
socket = server.accept();
server.close();
  throw new IOException(
    "Security violation: unexpected connection attempt by " +
    socket.getInetAddress().getHostAddress());

代码示例来源:origin: robovm/robovm

checkOpen();
if (isBound()) {
  throw new BindException("Socket is already bound");
  if ((addr = inetAddr.getAddress()) == null) {
    throw new SocketException("Host is unresolved: " + inetAddr.getHostName());
  port = inetAddr.getPort();
    impl.listen(backlog > 0 ? backlog : DEFAULT_BACKLOG);
  } catch (IOException e) {
    close();
    throw e;

代码示例来源:origin: apache/geode

public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
  List<GatewayTransportFilter> transportFilters, int socketBufferSize) throws IOException {
 if (transportFilters.isEmpty()) {
  return createServerSocket(nport, backlog, bindAddr, socketBufferSize);
 } else {
  printConfig();
  ServerSocket result = new TransportFilterServerSocket(transportFilters);
  result.setReuseAddress(true);
  // Set the receive buffer size before binding the socket so
  // that large buffers will be allocated on accepted sockets (see
  // java.net.ServerSocket.setReceiverBufferSize javadocs)
  result.setReceiveBufferSize(socketBufferSize);
  try {
   result.bind(new InetSocketAddress(bindAddr, nport), backlog);
  } catch (BindException e) {
   BindException throwMe =
     new BindException(String.format("Failed to create server socket on %s[%s]",
       bindAddr, Integer.valueOf(nport)));
   throwMe.initCause(e);
   throw throwMe;
  }
  return result;
 }
}

代码示例来源:origin: oci-pronghorn/Pronghorn

if ("0.0.0.0".equals(host)) {
  logger.warn("Developer used 0.0.0.0 as the host so this server is running on all known networks,\n              It is much more secure to define an explicit network binding like this eg. '10.*.*.*' ");
  endPoint = new InetSocketAddress(port);
  serverSocketChannel.socket().bind(endPoint);
  return endPoint;
} else {
    try{
      if (null == endPoint) {
        endPoint = new InetSocketAddress(host, port);		
        logger.trace("bind to {} ",endPoint);
      serverSocketChannel.socket().bind(endPoint);
      notConnected = false;
    } catch (BindException se) {
      if (System.currentTimeMillis() > timeout) {
        logger.warn("Timeout attempting to open open {}",endPoint,se.getMessage());
        coordinator.shutdown();
        throw se;

代码示例来源:origin: robovm/robovm

checkOpenAndCreate(true);
if (isBound()) {
  throw new BindException("Socket is already bound");
  if ((addr = inetAddr.getAddress()) == null) {
    throw new UnknownHostException("Host is unresolved: " + inetAddr.getHostName());
  port = inetAddr.getPort();

代码示例来源:origin: dCache/dcache

/**
 * Binds <code>socket</socket> to <code>address</code>. A port is
 * chosen from this port range. If the port range is [0,0], then a
 * free port is chosen by the OS.
 *
 * @throws IOException if the bind operation fails, or if the
 * socket is already bound.
 */
public int bind(ServerSocket socket, InetAddress address, int backlog)
  throws IOException
{
  int start = random();
  int port = start;
  do {
    try {
      socket.bind(new InetSocketAddress(address, port), backlog);
      return port;
    } catch (BindException e) {
    }
    port = succ(port);
  } while (port != start);
  throw new BindException("No free port within range");
}

代码示例来源:origin: baratine/baratine

throws IOException
ServerSocketChannel ss = ServerSocketChannel.open();
SocketAddress addr = new InetSocketAddress(host, port);
  ss.bind(addr);
 ss.bind(addr, listenBacklog);
  throw new BindException(L.l("{0}\nCan't bind to {1}:{2}.\nCheck for another server listening to that port.", e.getMessage(), host, String.valueOf(port)));
 else
  throw new BindException(L.l("{0}\nCan't bind to *:{1}.\nCheck for another server listening to that port.", e.getMessage(), String.valueOf(port)));

代码示例来源:origin: org.eclipse.hudson/hudson-core

/**
 * @param port Use 0 to choose a random port.
 */
public TcpSlaveAgentListener(int port) throws IOException {
  super("TCP slave agent listener port=" + port);
  try {
    serverSocket = new ServerSocket(port);
  } catch (BindException e) {
    throw (BindException) new BindException("Failed to listen on port " + port + " because it's already in use.").initCause(e);
  }
  this.configuredPort = port;
  LOGGER.info("JNLP slave agent listener started on TCP port " + getPort());
  start();
}

代码示例来源:origin: io.leopard/leopard-jetty

protected void checkOpened(int port) throws BindException {
  try {
    Socket s = new Socket();
    s.bind(new InetSocketAddress("0.0.0.0", port));
    s.close();
  }
  catch (java.net.BindException e) {
    String message = e.getMessage();
    if ("权限不够".equals(message) || "Permission denied".equals(message)) {
      throw new BindException("您无权限绑定" + port + "端口");
    }
    e.printStackTrace();
    throw new BindException("端口[" + port + "]已被占用.");
  }
  catch (Exception e) {
    e.printStackTrace();
    throw new BindException("端口[" + port + "]已被占用.");
  }
}

相关文章