java.net.PortUnreachableException Java Examples

The following examples show how to use java.net.PortUnreachableException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Socket.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public final int sendTo(ByteBuffer buf, int pos, int limit, InetAddress addr, int port) throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendTo(fd, buf, pos, limit, address, scopeId, port);
    if (res >= 0) {
        return res;
    }
    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendTo failed");
    }
    return ioResult("sendTo", res, SEND_TO_CONNECTION_RESET_EXCEPTION, SEND_TO_CLOSED_CHANNEL_EXCEPTION);
}
 
Example #2
Source File: Socket.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public final int sendToAddress(long memoryAddress, int pos, int limit, InetAddress addr, int port)
        throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendToAddress(fd, memoryAddress, pos, limit, address, scopeId, port);
    if (res >= 0) {
        return res;
    }
    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendToAddress failed");
    }
    return ioResult("sendToAddress", res,
            SEND_TO_ADDRESS_CONNECTION_RESET_EXCEPTION, SEND_TO_ADDRESS_CLOSED_CHANNEL_EXCEPTION);
}
 
Example #3
Source File: Socket.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public final int sendToAddresses(long memoryAddress, int length, InetAddress addr, int port) throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendToAddresses(fd, memoryAddress, length, address, scopeId, port);
    if (res >= 0) {
        return res;
    }

    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendToAddresses failed");
    }
    return ioResult("sendToAddresses", res,
            CONNECTION_RESET_EXCEPTION_SENDMSG, SEND_TO_ADDRESSES_CLOSED_CHANNEL_EXCEPTION);
}
 
Example #4
Source File: DatagramConnectNotExistsTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testConnectNotExists(Bootstrap cb) throws Throwable {
    final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            promise.trySuccess(cause);
        }
    });
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
    try {
        Channel datagramChannel = future.syncUninterruptibly().channel();
        Assert.assertTrue(datagramChannel.isActive());
        datagramChannel.writeAndFlush(
                Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
        if (!(datagramChannel instanceof OioDatagramChannel)) {
            Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
        }
    } finally {
        future.channel().close();
    }
}
 
Example #5
Source File: DatagramChannelImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private int sendFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
                                 InetSocketAddress target)
    throws IOException
{
    int pos = bb.position();
    int lim = bb.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    int written;
    try {
        int addressLen = targetSocketAddress(target);
        written = send0(fd, ((DirectBuffer)bb).address() + pos, rem,
                        targetSockAddr.address(), addressLen);
    } catch (PortUnreachableException pue) {
        if (isConnected())
            throw pue;
        written = rem;
    }
    if (written > 0)
        bb.position(pos + written);
    return written;
}
 
Example #6
Source File: SyslogAuditLogHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
void throwAsIoOrRuntimeException(Throwable t) throws IOException {
    if (t instanceof PortUnreachableException && transport == Transport.UDP) {
        //This is an exception that may or may not happen, see the javadoc for DatagramSocket.send().
        //We don't want something this unreliable polluting the failure count.
        //With UDP syslogging set up against a non-existent syslog server:
        //On OS X this exception never happens.
        //On Linux this seems to happens every other send, so we end up with a loop
        //    odd send works; failure count = 0
        //    even send fails; failure count = 1
        //    odd send works; failure count reset to 0
        //
        //Also, we don't want the full stack trace for this which would get printed by StandardFailureCountHandler.StandardFailureCountHandler.failure(),
        //which also handles the failure count, so we swallow the exception and print a warning.

        ControllerLogger.MGMT_OP_LOGGER.udpSyslogServerUnavailable(getName(), t.getLocalizedMessage());
        return;
    }
    if (t instanceof IOException) {
        throw (IOException)t;
    }
    if (t instanceof RuntimeException) {
        throw (RuntimeException)t;
    }
    throw new RuntimeException(t);
}
 
Example #7
Source File: NetworkBridge.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static int maybeThrowAfterRecvfrom(boolean isRead, boolean isConnected, ErrnoException errnoException) throws SocketException, SocketTimeoutException {
    if (isRead) {
        if (errnoException.errno == EAGAIN) {
            return 0;
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    } else {
        if (isConnected && errnoException.errno == ECONNREFUSED) {
            throw new PortUnreachableException("", errnoException);
        } else if (errnoException.errno == EAGAIN) {
            throw new SocketTimeoutException(errnoException);
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    }
}
 
Example #8
Source File: LocalVNS.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the next available port. The port is allocated from a cache of ports given to the VNS
 * service on startup.
 * 
 * @return - free port
 * 
 * @throws PortUnreachableException can't get port in configured range
 */
public synchronized int getPort() throws PortUnreachableException {
  boolean portAvailable = false;
  int retryCount = 0;
  while (!portAvailable) {
    onport++;
    if (onport > maxport) {
      onport = startport;
      retryCount++; // increment total number of times we cycled through available ports
    }
    if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_test_local_port__INFO",
              new Object[] { Thread.currentThread().getName(), String.valueOf(onport) });
    }
    // Check port availability
    portAvailable = isAvailable(onport);
    // In case ports are not available break out of the loop having tried 4 times
    // to acquire any of the ports in configured range
    if (retryCount > 3) {
      throw new PortUnreachableException(
              "Unable to aquire any of the ports in configured range:[" + startport + ".."
                      + maxport + "]");
    }
  }
  return onport;
}
 
Example #9
Source File: LocalVNS.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize local VNS instance with a range of ports, and the port for the VNS itself. A given
 * port is tested first for availability. If it is not available the next port is tested, until
 * one is found to be available.
 * 
 * @param aStartPort -
 *          starting port number used
 * @param aEndPort -
 *          end port number. Together with StartPort defines the range of ports (port pool)
 * @param aVNSPort -
 *          port on which this VNS will listen for requests
 * 
 * @throws PortUnreachableException unreachable port after retries
 */
public LocalVNS(int aStartPort, int aEndPort, int aVNSPort) throws PortUnreachableException {
  startport = aStartPort;
  maxport = aEndPort;
  vnsPort = aVNSPort;
  boolean vnsPortAvailable = false;
  int currentRetryCount = 0;
  // Loop until we find a valid port or hard limit of 100 tries is reached
  while (!vnsPortAvailable) {
    if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_test_vns_port__INFO",
              new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });
    }
    vnsPortAvailable = isAvailable(vnsPort);

    if (currentRetryCount > 100) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.SEVERE, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE,
              "UIMA_CPM_vns_port_not_available__SEVERE",
              new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });

      throw new PortUnreachableException("Unable to aquire a port for VNS Service");
    }
    if (!vnsPortAvailable) {
      vnsPort++;
    }
    currentRetryCount++;
  }
  if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
    UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
            "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_activating_vns_port__INFO",
            new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });
  }
  onport = startport;
}
 
Example #10
Source File: RPC.java    From RDFS with Apache License 2.0 5 votes vote down vote up
public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
  final boolean logDebug = LOG.isDebugEnabled();
  long startTime = 0;
  if (logDebug) {
    startTime = System.currentTimeMillis();
  }

  ObjectWritable value = null;
  try {
    value = (ObjectWritable) client.call(new Invocation(method, args),
        getAddress(), protocol, ticket, rpcTimeout);
  } catch (RemoteException re) {
    throw re;
  } catch (ConnectException ce) {
    needCheckDnsUpdate = true;
    throw ce;
  } catch (NoRouteToHostException nrhe) {
    needCheckDnsUpdate = true;
    throw nrhe;
  } catch (PortUnreachableException pue) {
    needCheckDnsUpdate = true;
    throw pue;
  }
  if (logDebug) {
    long callTime = System.currentTimeMillis() - startTime;
    LOG.debug("Call: " + method.getName() + " " + callTime);
  }
  return value.get();
}
 
Example #11
Source File: Client.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where 
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException, 
 * return a new one of the same type; Otherwise return an IOException.
 * 
 * @param addr target address
 * @param exception the relevant exception
 * @return an exception to throw
 */
private IOException wrapException(InetSocketAddress addr,
                                       IOException exception) {
  if (exception instanceof ConnectException) {
    //connection refused; include the host:port in the error
    return (ConnectException)new ConnectException(
         "Call to " + addr + " failed on connection exception: " + exception)
                  .initCause(exception);
  } else if (exception instanceof SocketTimeoutException) {
    return (SocketTimeoutException)new SocketTimeoutException(
         "Call to " + addr + " failed on socket timeout exception: "
                    + exception).initCause(exception);
  } else if (exception instanceof NoRouteToHostException) {
    return (NoRouteToHostException)new NoRouteToHostException(
         "Call to " + addr + " failed on NoRouteToHostException exception: "
                    + exception).initCause(exception);
  } else if (exception instanceof PortUnreachableException) {
    return (PortUnreachableException)new PortUnreachableException(
         "Call to " + addr + " failed on PortUnreachableException exception: "
                    + exception).initCause(exception);
  } else {
    return (IOException)new IOException(
         "Call to " + addr + " failed on local exception: " + exception)
                               .initCause(exception);

  }
}
 
Example #12
Source File: UdpDataSender.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void sendPacket(Object message) {

        final InetSocketAddress inetSocketAddress = socketAddressProvider.resolve();
        if (inetSocketAddress.getAddress() == null) {
            logger.info("dns lookup fail host:{}", inetSocketAddress);
            return;
        }

        final ByteMessage byteMessage = messageSerializer.serializer(message);
        if (byteMessage == null) {
            logger.warn("sendPacket fail. message:{}", message != null ? message.getClass() : null);
            if (logger.isDebugEnabled()) {
                logger.debug("unknown message:{}", message);
            }
            return;
        }
        final DatagramPacket packet = preparePacket(inetSocketAddress, byteMessage);

        try {
            udpSocket.send(packet);
            if (isDebug) {
                logger.debug("Data sent. size:{}, {}", byteMessage.getLength(), message);
            }
        } catch (PortUnreachableException pe) {
            this.socketAddressProvider.handlePortUnreachable();
            logger.info("packet send error. size:{}, {}", byteMessage.getLength(), message, pe);
        } catch (IOException e) {
            logger.info("packet send error. size:{}, {}", byteMessage.getLength(), message, e);
        }

    }
 
Example #13
Source File: MultiSndDestination.java    From aeron with Apache License 2.0 5 votes vote down vote up
static int send(
    final DatagramChannel datagramChannel,
    final ByteBuffer buffer,
    final SendChannelEndpoint channelEndpoint,
    final int bytesToSend,
    final int position,
    final InetSocketAddress destination)
{
    int bytesSent = 0;
    try
    {
        if (datagramChannel.isOpen())
        {
            buffer.position(position);
            channelEndpoint.sendHook(buffer, destination);
            bytesSent = datagramChannel.send(buffer, destination);
        }
    }
    catch (final PortUnreachableException ignore)
    {
    }
    catch (final IOException ex)
    {
        sendError(bytesToSend, ex, destination);
    }

    return bytesSent;
}
 
Example #14
Source File: SendChannelEndpoint.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Send contents of a {@link ByteBuffer} to connected address.
 * This is used on the sender side for performance over send(ByteBuffer, SocketAddress).
 *
 * @param buffer to send
 * @return number of bytes sent
 */
public int send(final ByteBuffer buffer)
{
    int bytesSent = 0;

    if (null != sendDatagramChannel)
    {
        final int bytesToSend = buffer.remaining();

        if (null == multiSndDestination)
        {
            try
            {
                sendHook(buffer, connectAddress);
                if (sendDatagramChannel.isConnected())
                {
                    bytesSent = sendDatagramChannel.write(buffer);
                }
            }
            catch (final PortUnreachableException ignore)
            {
            }
            catch (final IOException ex)
            {
                sendError(bytesToSend, ex, connectAddress);
            }
        }
        else
        {
            bytesSent = multiSndDestination.send(sendDatagramChannel, buffer, this, bytesToSend);
        }
    }

    return bytesSent;
}
 
Example #15
Source File: TcpCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void connectPortUnreachable() throws Exception {
    Mockito.doThrow(new PortUnreachableException()).when(mockSocket).connect(Mockito.any());

    final TcpCollector.ConnectDatum result;
    try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) {
        result = tcpCollector.tryConnect(mockSocket);
    }

    assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.PORT_UNREACHABLE));
    Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress));
    Mockito.verifyNoMoreInteractions(mockSocket);
}
 
Example #16
Source File: StatsdMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void prepareUdpClient(Publisher<String> publisher) {
    AtomicReference<UdpClient> udpClientReference = new AtomicReference<>();
    UdpClient udpClient = UdpClient.create()
            .host(statsdConfig.host())
            .port(statsdConfig.port())
            .handle((in, out) -> out
                    .sendString(publisher)
                    .neverComplete()
                    .retryWhen(Retry.indefinitely().filter(throwable -> throwable instanceof PortUnreachableException))
            )
            .doOnDisconnected(connection -> connectAndSubscribe(udpClientReference.get()));
    udpClientReference.set(udpClient);
    connectAndSubscribe(udpClient);
}
 
Example #17
Source File: AbstractNioMessageChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
protected boolean closeOnReadError(Throwable cause) {
    // ServerChannel should not be closed even on IOException because it can often continue
    // accepting incoming connections. (e.g. too many open files)
    return cause instanceof IOException &&
            !(cause instanceof PortUnreachableException) &&
            !(this instanceof ServerChannel);
}
 
Example #18
Source File: NIOUtil.java    From jlibs with Apache License 2.0 4 votes vote down vote up
public static boolean isConnectionFailure(Throwable thr){
    return thr instanceof UnresolvedAddressException
            || thr instanceof ConnectException
            || thr instanceof PortUnreachableException;
}
 
Example #19
Source File: BazaarRestClient.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private <T> RestResult<T> execute( String httpMethod, String url, Object body, Class<T> clazz, boolean encrypt )
{
    log.info( "{} {}", httpMethod, url );

    WebClient webClient = null;
    Response response = null;
    RestResult<T> restResult = new RestResult<>( HttpStatus.SC_INTERNAL_SERVER_ERROR );

    try
    {
        webClient = configManager.getTrustedWebClientWithAuth( url, configManager.getBazaarIp() );

        Object requestBody = encrypt ? encryptBody( body ) : body;

        response = webClient.invoke( httpMethod, requestBody );

        // retry on 503 http code >>>
        int attemptNo = 1;
        while ( response.getStatus() == HttpStatus.SC_SERVICE_UNAVAILABLE && attemptNo < MAX_ATTEMPTS )
        {
            attemptNo++;
            response = webClient.invoke( httpMethod, requestBody );
            TaskUtil.sleep( 500 );
        }
        // <<< retry on 503 http code

        log.info( "response.status: {} - {}", response.getStatus(), response.getStatusInfo().getReasonPhrase() );

        restResult = handleResponse( response, clazz, encrypt );
    }
    catch ( Exception e )
    {
        if ( response != null )
        {
            restResult.setReasonPhrase( response.getStatusInfo().getReasonPhrase() );
        }

        Throwable rootCause = ExceptionUtil.getRootCauze( e );
        if ( rootCause instanceof ConnectException || rootCause instanceof UnknownHostException
                || rootCause instanceof BindException || rootCause instanceof NoRouteToHostException
                || rootCause instanceof PortUnreachableException || rootCause instanceof SocketTimeoutException )
        {
            restResult.setError( CONNECTION_EXCEPTION_MARKER );
        }
        else
        {
            restResult.setError( ERROR + e.getMessage() );
        }

        log.error( ERROR + e.getMessage() );
    }
    finally
    {
        close( webClient, response );
    }

    return restResult;
}