Java Code Examples for java.net.SocketException
The following examples show how to use
java.net.SocketException. These examples are extracted from open source projects.
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 Project: uuid-creator Source File: NetworkData.java License: MIT License | 8 votes |
/** * Returns a list of {@link NetworkData}. * * This method iterates over all the network interfaces to return those that * are up and running. * * NOTE: it may be VERY EXPENSIVE on Windows systems, because that OS * creates a lot of virtual network interfaces. * * @return a list of {@link NetworkData} */ public static List<NetworkData> getNetworkDataList() { try { InetAddress inetAddress = InetAddress.getLocalHost(); List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); HashSet<NetworkData> networkDataHashSet = new HashSet<>(); for (NetworkInterface networkInterface : networkInterfaces) { NetworkData networkData = buildNetworkData(networkInterface, inetAddress); if (networkData != null) { networkDataHashSet.add(networkData); } } return new ArrayList<>(networkDataHashSet); } catch (SocketException | NullPointerException | UnknownHostException e) { return Collections.emptyList(); } }
Example 2
Source Project: monsoon Source File: TcpCollectorTest.java License: BSD 3-Clause "New" or "Revised" License | 7 votes |
@Test public void connectFailed_withSocketException() throws Exception { Mockito.doThrow(new SocketException()).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.CONNECT_FAILED)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); }
Example 3
Source Project: openjdk-8-source Source File: HttpsClient.java License: GNU General Public License v2.0 | 6 votes |
/** * The following method, createSocket, is defined in NetworkClient * and overridden here so that the socket facroty is used to create * new sockets. */ @Override protected Socket createSocket() throws IOException { try { return sslSocketFactory.createSocket(); } catch (SocketException se) { // // bug 6771432 // javax.net.SocketFactory throws a SocketException with an // UnsupportedOperationException as its cause to indicate that // unconnected sockets have not been implemented. // Throwable t = se.getCause(); if (t != null && t instanceof UnsupportedOperationException) { return super.createSocket(); } else { throw se; } } }
Example 4
Source Project: ethsigner Source File: TransactionTransmitter.java License: Apache License 2.0 | 6 votes |
private boolean populateNonce() { try { transaction.updateNonce(); return true; } catch (final RuntimeException e) { LOG.warn("Unable to get nonce from web3j provider.", e); final Throwable cause = e.getCause(); if (cause instanceof SocketException || cause instanceof SocketTimeoutException || cause instanceof TimeoutException) { routingContext.fail( GATEWAY_TIMEOUT.code(), new JsonRpcException(CONNECTION_TO_DOWNSTREAM_NODE_TIMED_OUT)); } else if (cause instanceof SSLHandshakeException) { routingContext.fail(BAD_GATEWAY.code(), cause); } else { routingContext.fail(GATEWAY_TIMEOUT.code(), new JsonRpcException(INTERNAL_ERROR)); } } catch (final Throwable thrown) { LOG.debug("Failed to encode/serialize transaction: {}", transaction, thrown); routingContext.fail(BAD_REQUEST.code(), new JsonRpcException(INTERNAL_ERROR)); } return false; }
Example 5
Source Project: tomcatsrc Source File: SocketProperties.java License: Apache License 2.0 | 6 votes |
public void setProperties(Socket socket) throws SocketException{ if (rxBufSize != null) socket.setReceiveBufferSize(rxBufSize.intValue()); if (txBufSize != null) socket.setSendBufferSize(txBufSize.intValue()); if (ooBInline !=null) socket.setOOBInline(ooBInline.booleanValue()); if (soKeepAlive != null) socket.setKeepAlive(soKeepAlive.booleanValue()); if (performanceConnectionTime != null && performanceLatency != null && performanceBandwidth != null) socket.setPerformancePreferences( performanceConnectionTime.intValue(), performanceLatency.intValue(), performanceBandwidth.intValue()); if (soReuseAddress != null) socket.setReuseAddress(soReuseAddress.booleanValue()); if (soLingerOn != null && soLingerTime != null) socket.setSoLinger(soLingerOn.booleanValue(), soLingerTime.intValue()); if (soTimeout != null && soTimeout.intValue() >= 0) socket.setSoTimeout(soTimeout.intValue()); if (tcpNoDelay != null) socket.setTcpNoDelay(tcpNoDelay.booleanValue()); }
Example 6
Source Project: Bytecoder Source File: DatagramSocketAdaptor.java License: Apache License 2.0 | 6 votes |
@Override public void receive(DatagramPacket p) throws IOException { // get temporary direct buffer with a capacity of p.bufLength int bufLength = DatagramPackets.getBufLength(p); ByteBuffer bb = Util.getTemporaryDirectBuffer(bufLength); try { long nanos = MILLISECONDS.toNanos(timeout); SocketAddress sender = dc.blockingReceive(bb, nanos); bb.flip(); synchronized (p) { // copy bytes to the DatagramPacket and set length int len = Math.min(bb.limit(), DatagramPackets.getBufLength(p)); bb.get(p.getData(), p.getOffset(), len); DatagramPackets.setLength(p, len); // sender address p.setSocketAddress(sender); } } catch (ClosedChannelException e) { var exc = new SocketException("Socket closed"); exc.initCause(e); throw exc; } finally { Util.offerFirstTemporaryDirectBuffer(bb); } }
Example 7
Source Project: jdk8u-jdk Source File: HttpsClient.java License: GNU General Public License v2.0 | 6 votes |
/** * The following method, createSocket, is defined in NetworkClient * and overridden here so that the socket facroty is used to create * new sockets. */ @Override protected Socket createSocket() throws IOException { try { return sslSocketFactory.createSocket(); } catch (SocketException se) { // // bug 6771432 // javax.net.SocketFactory throws a SocketException with an // UnsupportedOperationException as its cause to indicate that // unconnected sockets have not been implemented. // Throwable t = se.getCause(); if (t != null && t instanceof UnsupportedOperationException) { return super.createSocket(); } else { throw se; } } }
Example 8
Source Project: jdk8u60 Source File: Util.java License: GNU General Public License v2.0 | 6 votes |
/** * Returns a list of all the addresses on the system. * @param inclLoopback * if {@code true}, include the loopback addresses * @param ipv4Only * it {@code true}, only IPv4 addresses will be included */ static List<InetAddress> getAddresses(boolean inclLoopback, boolean ipv4Only) throws SocketException { ArrayList<InetAddress> list = new ArrayList<InetAddress>(); Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInf : Collections.list(nets)) { Enumeration<InetAddress> addrs = netInf.getInetAddresses(); for (InetAddress addr : Collections.list(addrs)) { if (!list.contains(addr) && (inclLoopback ? true : !addr.isLoopbackAddress()) && (ipv4Only ? (addr instanceof Inet4Address) : true)) { list.add(addr); } } } return list; }
Example 9
Source Project: CSipSimple Source File: Local.java License: GNU General Public License v3.0 | 6 votes |
public String getLocalIpAddresses() { ArrayList<String> addresses = new ArrayList<String>(); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { addresses.add(inetAddress.getHostAddress().toString()); } } } } catch (SocketException ex) { Log.e(THIS_FILE, "Impossible to get ip address", ex); } return TextUtils.join("\n", addresses); }
Example 10
Source Project: FimiX8-RE Source File: WiFiUtils.java License: MIT License | 6 votes |
public static String getPhoneIp(Context application) { WifiManager wifiManager = (WifiManager) application.getSystemService("wifi"); if (wifiManager.isWifiEnabled()) { return intToIp(wifiManager.getConnectionInfo().getIpAddress()); } try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { Enumeration<InetAddress> enumIpAddr = ((NetworkInterface) en.nextElement()).getInetAddresses(); while (enumIpAddr.hasMoreElements()) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException e) { e.printStackTrace(); } return null; }
Example 11
Source Project: commons-jcs Source File: HostNameUtil.java License: Apache License 2.0 | 6 votes |
/** * On systems with multiple network interfaces and mixed IPv6/IPv4 get a valid network * interface for binding to multicast * * @return a network interface suitable for multicast * @throws SocketException if a problem occurs while reading the network interfaces */ public static NetworkInterface getMulticastNetworkInterface() throws SocketException { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); Enumeration<InetAddress> addressesFromNetworkInterface = networkInterface.getInetAddresses(); while (addressesFromNetworkInterface.hasMoreElements()) { InetAddress inetAddress = addressesFromNetworkInterface.nextElement(); if (inetAddress.isSiteLocalAddress() && !inetAddress.isAnyLocalAddress() && !inetAddress.isLinkLocalAddress() && !inetAddress.isLoopbackAddress() && !inetAddress.isMulticastAddress()) { return networkInterface; } } } return null; }
Example 12
Source Project: openjsse Source File: SSLSocketImpl.java License: GNU General Public License v2.0 | 6 votes |
/** * Layer SSL traffic over an existing connection, rather than * creating a new connection. * * The existing connection may be used only for SSL traffic (using this * SSLSocket) until the SSLSocket.close() call returns. However, if a * protocol error is detected, that existing connection is automatically * closed. * <p> * This particular constructor always uses the socket in the * role of an SSL client. It may be useful in cases which start * using SSL after some initial data transfers, for example in some * SSL tunneling applications or as part of some kinds of application * protocols which negotiate use of a SSL based security. */ SSLSocketImpl(SSLContextImpl sslContext, Socket sock, String peerHost, int port, boolean autoClose) throws IOException { super(sock); // We always layer over a connected socket if (!sock.isConnected()) { throw new SocketException("Underlying socket is not connected"); } this.sslContext = sslContext; HandshakeHash handshakeHash = new HandshakeHash(); this.conContext = new TransportContext(sslContext, this, new SSLSocketInputRecord(handshakeHash), new SSLSocketOutputRecord(handshakeHash), true); this.peerHost = peerHost; this.autoClose = autoClose; doneConnect(); }
Example 13
Source Project: davmail Source File: FolderLoadThread.java License: GNU General Public License v2.0 | 6 votes |
/** * Load folder in a separate thread. * * @param folder current folder * @param outputStream client connection * @throws InterruptedException on error * @throws IOException on error */ public static void loadFolder(ExchangeSession.Folder folder, OutputStream outputStream) throws InterruptedException, IOException { FolderLoadThread folderLoadThread = new FolderLoadThread(currentThread().getName(), folder); folderLoadThread.start(); while (!folderLoadThread.isComplete) { folderLoadThread.join(20000); LOGGER.debug("Still loading " + folder.folderPath + " (" + folder.count() + " messages)"); if (Settings.getBooleanProperty("davmail.enableKeepAlive", false)) { try { outputStream.write(' '); outputStream.flush(); } catch (SocketException e) { folderLoadThread.interrupt(); throw e; } } } if (folderLoadThread.exception != null) { throw folderLoadThread.exception; } }
Example 14
Source Project: orWall Source File: NetworkHelper.java License: GNU General Public License v3.0 | 6 votes |
public static String getMask(String intf){ try { NetworkInterface ntwrk = NetworkInterface.getByName(intf); Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator(); while (addrList.hasNext()) { InterfaceAddress addr = addrList.next(); InetAddress ip = addr.getAddress(); if (ip instanceof Inet4Address) { String mask = ip.getHostAddress() + "/" + addr.getNetworkPrefixLength(); return mask; } } } catch (SocketException e) { e.printStackTrace(); } return null; }
Example 15
Source Project: lsp4j Source File: RemoteEndpointTest.java License: Eclipse Public License 2.0 | 6 votes |
@Test public void testOutputStreamClosed() throws Exception { LogMessageAccumulator logMessages = new LogMessageAccumulator(); try { logMessages.registerTo(RemoteEndpoint.class); TestEndpoint endp = new TestEndpoint(); MessageConsumer consumer = new MessageConsumer() { @Override public void consume(Message message) throws JsonRpcException { throw new JsonRpcException(new SocketException("Socket closed")); } }; RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp); endpoint.notify("foo", null); logMessages.await(Level.INFO, "Failed to send notification message."); } finally { logMessages.unregister(); } }
Example 16
Source Project: myqq Source File: UDP.java License: MIT License | 6 votes |
/** * 获取可用的端口号 */ public void getMyUsefulPort() { while(true) { try { // 实例化一个DatagramSocket socket = new DatagramSocket(myPort); break; } catch (SocketException e) { myPort++; } } }
Example 17
Source Project: radar Source File: IPUtil.java License: Apache License 2.0 | 6 votes |
private static String getLinuxLocalIP() { String ip = ""; try { Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces(); while (e1.hasMoreElements()) { NetworkInterface ni = e1.nextElement(); if (netWorkCard.equals(ni.getName()) || NETWORK_CARD.equals(ni.getName()) || NETWORK_CARD_BAND.equals(ni.getName())) { Enumeration<InetAddress> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ia = e2.nextElement(); if (ia instanceof Inet6Address) { continue; } ip = ia.getHostAddress(); } break; } else { continue; } } } catch (SocketException e) { e.printStackTrace(); } return ip; }
Example 18
Source Project: AndroidRipper Source File: RipperServiceSocket.java License: GNU Affero General Public License v3.0 | 6 votes |
/** * Send a DESCRIBE Message. * * Call describe(MAX_RETRY = 5) * * @return * @throws SocketException */ public String describe() throws SocketException { String desc = null; try { desc = describe(3); } catch (RuntimeException rex) { if( desc == null ){ //single retry desc = describe(3); } } return desc; }
Example 19
Source Project: flow Source File: AbstractTestBenchTest.java License: Apache License 2.0 | 6 votes |
/** * Returns host address that can be targeted from the outside, like from a * test hub. * * @return host address * @throws RuntimeException * if host name could not be determined or * {@link SocketException} was caught during the determination. */ protected String getCurrentHostAddress() { try { Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface nwInterface = interfaces.nextElement(); if (!nwInterface.isUp() || nwInterface.isLoopback() || nwInterface.isVirtual()) { continue; } Optional<String> address = getHostAddress(nwInterface); if (address.isPresent()) { return address.get(); } } } catch (SocketException e) { throw new RuntimeException("Could not find the host name", e); } throw new RuntimeException( "No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found."); }
Example 20
Source Project: twister2 Source File: ResourceSchedulerUtils.java License: Apache License 2.0 | 6 votes |
/** * get ipv4 address of first matching network interface in the given list * network interface can not be loop back and it has to be up * @param interfaceNames * @return */ public static String getLocalIPFromNetworkInterfaces(List<String> interfaceNames) { try { for (String nwInterfaceName: interfaceNames) { NetworkInterface networkInterface = NetworkInterface.getByName(nwInterfaceName); if (networkInterface != null && !networkInterface.isLoopback() && networkInterface.isUp()) { List<InterfaceAddress> addressList = networkInterface.getInterfaceAddresses(); for (InterfaceAddress adress: addressList) { if (isValidIPv4(adress.getAddress().getHostAddress())) { return adress.getAddress().getHostAddress(); } } } } } catch (SocketException e) { LOG.log(Level.SEVERE, "Error retrieving network interface list", e); } return null; }
Example 21
Source Project: jdk8u-dev-jdk Source File: SctpChannelImpl.java License: GNU General Public License v2.0 | 6 votes |
@Override public Set<SocketAddress> getRemoteAddresses() throws IOException { synchronized (stateLock) { if (!isOpen()) throw new ClosedChannelException(); if (!isConnected() || isShutdown) return Collections.emptySet(); try { return SctpNet.getRemoteAddresses(fdVal, 0/*unused*/); } catch (SocketException unused) { /* an open connected channel should always have remote addresses */ return remoteAddresses; } } }
Example 22
Source Project: HaoReader Source File: NetworkUtil.java License: GNU General Public License v3.0 | 6 votes |
/** * Get local Ip address. */ public static InetAddress getLocalIPAddress() { Enumeration<NetworkInterface> enumeration = null; try { enumeration = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); } if (enumeration != null) { while (enumeration.hasMoreElements()) { NetworkInterface nif = enumeration.nextElement(); Enumeration<InetAddress> inetAddresses = nif.getInetAddresses(); if (inetAddresses != null) { while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && isIPv4Address(inetAddress.getHostAddress())) { return inetAddress; } } } } } return null; }
Example 23
Source Project: dragonwell8_jdk Source File: ResourceManager.java License: GNU General Public License v2.0 | 5 votes |
public static void beforeUdpCreate() throws SocketException { if (System.getSecurityManager() != null) { if (numSockets.incrementAndGet() > maxSockets) { numSockets.decrementAndGet(); throw new SocketException("maximum number of DatagramSockets reached"); } } }
Example 24
Source Project: xian Source File: GelfTCPSender.java License: Apache License 2.0 | 5 votes |
protected void write(ByteBuffer buffer) throws IOException { while (buffer.hasRemaining()) { int written = channel().write(buffer); if (written < 0 || !isConnected()) { // indicator the socket was closed Closer.close(channel()); throw new SocketException("Cannot write buffer to channel"); } } }
Example 25
Source Project: java-client-api Source File: HostAvailabilityListener.java License: Apache License 2.0 | 5 votes |
/** * Manages refreshing the forests and hosts and retrying events after a host * becomes unavailable. * @param moveMgr the DataMovementManager (used to call readForestConfig to reset after black-listing an unavailable host) */ public HostAvailabilityListener(DataMovementManager moveMgr) { if (moveMgr == null) throw new IllegalArgumentException("moveMgr must not be null"); this.moveMgr = moveMgr; if (moveMgr.getConnectionType() == DatabaseClient.ConnectionType.DIRECT) { hostUnavailableExceptions.add(SocketException.class); hostUnavailableExceptions.add(SSLException.class); hostUnavailableExceptions.add(UnknownHostException.class); } }
Example 26
Source Project: Komondor Source File: NamedPipeSocketFactory.java License: GNU General Public License v3.0 | 5 votes |
/** * @see com.mysql.jdbc.SocketFactory#connect(String, Properties) */ public Socket connect(String host, int portNumber /* ignored */, Properties props) throws SocketException, IOException { String namedPipePath = props.getProperty(NAMED_PIPE_PROP_NAME); if (namedPipePath == null) { namedPipePath = "\\\\.\\pipe\\MySQL"; } else if (namedPipePath.length() == 0) { throw new SocketException(Messages.getString("NamedPipeSocketFactory.2") + NAMED_PIPE_PROP_NAME + Messages.getString("NamedPipeSocketFactory.3")); } this.namedPipeSocket = new NamedPipeSocket(namedPipePath); return this.namedPipeSocket; }
Example 27
Source Project: kite Source File: HiveService.java License: Apache License 2.0 | 5 votes |
@Override protected TSocket acceptImpl() throws TTransportException { TSocket ts = super.acceptImpl(); try { ts.getSocket().setKeepAlive(true); } catch (SocketException e) { throw new TTransportException(e); } return ts; }
Example 28
Source Project: gemfirexd-oss Source File: ClientConnection.java License: Apache License 2.0 | 5 votes |
private void setTimeout(int milliseconds) throws SQLException { // input and output protocol are identical in our usage TTransport socket = this.clientService.getInputProtocol().getTransport(); if (socket instanceof SocketTimeout) { try { ((SocketTimeout)socket).setSoTimeout(milliseconds); } catch (SocketException se) { throw ThriftExceptionUtil.newSQLException(SQLState.SOCKET_EXCEPTION, se, se.getMessage()); } } }
Example 29
Source Project: openjdk-8-source Source File: SnmpAdaptorServer.java License: GNU General Public License v2.0 | 5 votes |
/** * Open informSocket if it's not already done. */ synchronized void openInformSocketIfNeeded() throws SocketException { if (informSession == null) { informSession = new SnmpSession(this) ; if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag, "openInformSocketIfNeeded", "to send inform requests and receive inform responses"); } } }
Example 30
Source Project: openhab1-addons Source File: ModbusTCPListener.java License: Eclipse Public License 2.0 | 5 votes |
/** * Accepts incoming connections and handles then with * <tt>TCPConnectionHandler</tt> instances. */ @Override public void run() { try { /* * A server socket is opened with a connectivity queue of a size specified * in int floodProtection. Concurrent login handling under normal circumstances * should be allright, denial of service attacks via massive parallel * program logins can probably be prevented. */ m_ServerSocket = new ServerSocket(m_Port, m_FloodProtection, m_Address); logger.debug("Listenening to {} (Port {})", m_ServerSocket.toString(), m_Port); // Infinite loop, taking care of resources in case of a lot of parallel logins do { Socket incoming = m_ServerSocket.accept(); logger.debug("Making new connection {}", incoming.toString()); if (m_Listening) { // FIXME: Replace with object pool due to resource issues m_ThreadPool.execute(new TCPConnectionHandler(m_ConnectionFactory.create(incoming))); count(); } else { // just close the socket incoming.close(); } } while (m_Listening); } catch (SocketException iex) { if (!m_Listening) { return; } else { iex.printStackTrace(); } } catch (IOException e) { // FIXME: this is a major failure, how do we handle this } }