/** * Get ipv4 address. * * @return */ @Nullable public static String getIPV4() { try { Enumeration<NetworkInterface> net = NetworkInterface.getNetworkInterfaces(); while (net.hasMoreElements()) { NetworkInterface networkInterface = net.nextElement(); Enumeration<InetAddress> add = networkInterface.getInetAddresses(); while (add.hasMoreElements()) { InetAddress a = add.nextElement(); if (!a.isLoopbackAddress() && !a.getHostAddress().contains(":")) { if (Debug.debug) { Log.d(TAG, "getIPV4 : " + a.getHostAddress()); } return a.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } return null; }
public static String getGPRSIP() { String ip = null; try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { for (Enumeration<InetAddress> enumIpAddr = en.nextElement().getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { ip = inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); ip = null; } return ip; }
/** * 获取GSM网络的IP地址 */ public static String getMobileIP() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = (NetworkInterface) en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ipaddress = inetAddress.getHostAddress().toString(); return ipaddress; } } } } catch (SocketException ex) { Log.e("getMobileIP", "Exception in Get IP Address: " + ex.toString()); } return ""; }
/** * 得到ip地址 * * @return */ public static String getLocalIpAddress() { String ret = ""; 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()) { ret = inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return ret; }
/** * Creates the datagram socket. */ @Override protected void doBind() throws CommunicationException, InterruptedException { try { synchronized (this) { socket = new DatagramSocket(port, address) ; } dbgTag = makeDebugTag(); } catch (SocketException e) { if (e.getMessage().equals(InterruptSysCallMsg)) throw new InterruptedException(e.toString()) ; else { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, dbgTag, "doBind", "cannot bind on port " + port); } throw new CommunicationException(e) ; } } }
/** * 获取设备IP * * @return */ public String getDevicesIp() { 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()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return null; }
/** * 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; }
private String getActiveNetworkInterfaceIP() throws SocketException { Enumeration<NetworkInterface> networkInterface = NetworkInterface.getNetworkInterfaces(); String ipv6AddrStr = null; while (networkInterface.hasMoreElements()) { NetworkInterface nic = networkInterface.nextElement(); if (nic.isUp() && !nic.isLoopback()) { Enumeration<InetAddress> inet = nic.getInetAddresses(); while (inet.hasMoreElements()) { InetAddress addr = inet.nextElement(); if (addr instanceof Inet4Address && !addr.isLinkLocalAddress()) { return addr.getHostAddress(); }else if (addr instanceof Inet6Address && !addr.isLinkLocalAddress()) { /* We save last seen IPv6 address which we will return if we do not find any interface with IPv4 address. */ ipv6AddrStr = addr.getHostAddress(); } } } } return ipv6AddrStr; }
/** * 取得本机的IP,并把结果放到static变量中. * * @return 如果有多个IP地址返回外网的IP,多个外网IP返回第一个IP(在多网管等特殊情况下) * @throws SocketException */ public static String getRealIpWithStaticCache() { if (cachedIp == null) { synchronized (syncObject) { try { cachedIp = getRealIp(); } catch (SocketException ex) { LOG.error("", ex); cachedIp = "127.0.0.1"; } } return cachedIp; } else { return cachedIp; } }
@Test public void testNetworkInterfaces() throws SocketException { Supplier<Stream<NetworkInterface>> ss = () -> { try { return NetworkInterface.networkInterfaces() .filter(ni -> isIncluded(ni)); } catch (SocketException e) { throw new RuntimeException(e); } }; Collection<NetworkInterface> enums = Collections.list(NetworkInterface.getNetworkInterfaces()); Collection<NetworkInterface> expected = new ArrayList<>(); enums.forEach(ni -> { if (isIncluded(ni)) { expected.add(ni); } }); withData(TestData.Factory.ofSupplier("Top-level network interfaces", ss)) .stream(s -> s) .expectedResult(expected) .exercise(); }
public static String getLocalIpAddressV4() { String ip = ""; 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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) //这里做了一步IPv4的判定 if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { ip = inetAddress.getHostAddress().toString(); return ip; } } } } catch (SocketException e) { // Log.i("SocketException--->", ""+e.getLocalizedMessage()); return "ip is error"; } return ip; }
public static String getIpAddress() { 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() && (inetAddress instanceof Inet4Address)) { // we get both ipv4 and ipv6, we want ipv4 return inetAddress.getHostAddress(); } } } } catch (SocketException e) { Log.e(TAG,"getIpAddress", e); } return null; }
/** format network interface flags */ private static String formatFlags(NetworkInterface nic) throws SocketException { StringBuilder flags = new StringBuilder(); if (nic.isUp()) { flags.append("UP "); } if (nic.supportsMulticast()) { flags.append("MULTICAST "); } if (nic.isLoopback()) { flags.append("LOOPBACK "); } if (nic.isPointToPoint()) { flags.append("POINTOPOINT "); } if (nic.isVirtual()) { flags.append("VIRTUAL "); } flags.append("mtu:" + nic.getMTU()); flags.append(" index:" + nic.getIndex()); return flags.toString(); }
/** * 获取GPRS连接的情况的IP * * @return */ private static String getGPRSIpAddress() { String ip = ""; 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() && inetAddress.getHostAddress() != null) { ip = inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("WifiPreference IpAddress", ex.toString()); } return ip == null ? "" : ip; }
public static void initSocket(final Socket s, final String host, final int port, final JSONObject error) throws SocketException, IOException { final SocketAddress endpoint = new InetSocketAddress(host, port); try { s.setSoTimeout(1000); s.connect(endpoint, 1000); } catch (SocketTimeoutException | ConnectException | UnknownHostException e) { error.put("class", e.getClass().getSimpleName()); error.put("message", e.getMessage()); } }
protected String receiveToPossible(MoreExecutor more) throws SocketException, ReceivingTimeoutException, ConsoleException, IOException { TelnetByteArray temp = new TelnetByteArray(); while (true) { read(temp, TIMEOUT_TIME); byte[] bytes = temp.toByteArray(); if (more.isMoreInput(bytes)) { try { log.debug("more: wait " + this.MORE_INTERVAL + " ms to next."); Thread.sleep(this.MORE_INTERVAL); } catch (InterruptedException e) { } send(more.getSendMoreBytes(new String(bytes))); } else { break; } } this.lastAccess = System.currentTimeMillis(); log.debug("command lapse: " + (this.lastAccess - this.beginAccess) + " ms."); return new String(temp.toByteArray()); }
/** * Test that we can't accidentally connect back to the connecting socket due * to a quirk in the TCP spec. * * This is a regression test for HADOOP-6722. */ @Test public void testAvoidLoopbackTcpSockets() throws Exception { Configuration conf = new Configuration(); Socket socket = NetUtils.getDefaultSocketFactory(conf) .createSocket(); socket.bind(new InetSocketAddress("127.0.0.1", 0)); System.err.println("local address: " + socket.getLocalAddress()); System.err.println("local port: " + socket.getLocalPort()); try { NetUtils.connect(socket, new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()), 20000); socket.close(); fail("Should not have connected"); } catch (ConnectException ce) { System.err.println("Got exception: " + ce); assertTrue(ce.getMessage().contains("resulted in a loopback")); } catch (SocketException se) { // Some TCP stacks will actually throw their own Invalid argument exception // here. This is also OK. assertTrue(se.getMessage().contains("Invalid argument")); } }
public static String getHostIPv4Address() { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface ni : interfaces) { List<InetAddress> addresses = Collections.list(ni.getInetAddresses()); for (InetAddress addr : addresses) { if (!addr.isLoopbackAddress()) { String strAddr = addr.getHostAddress(); if(!strAddr.contains(":")) { return strAddr; } } } } } catch (SocketException e) { e.printStackTrace(); } return "0.0.0.0"; }
static String wifiIpAddress() { //ADAPTED FROM: http://stackoverflow.com/questions/9573196/how-to-get-the-ip-of-the-wifi-hotspot-in-android try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); if (intf.getName().contains("wlan") || intf.getName().contains("ap")) { Log.d("WIFI_IP", intf.getName()); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) { Log.d("WIFI_IP_ADDRESS", inetAddress.getHostAddress()); return inetAddress.getHostAddress(); } } } } } catch (SocketException ex) { Log.e(APP_IDENTIFIER, "Utils -> wifiIpAddress".concat(ex.getMessage())); } return null; }
/** Returns all site-local scope (private) addresses for interfaces that are up. */ static InetAddress[] getSiteLocalAddresses() throws SocketException { List<InetAddress> list = new ArrayList<>(); for (NetworkInterface intf : getInterfaces()) { if (intf.isUp()) { for (InetAddress address : Collections.list(intf.getInetAddresses())) { if (address.isSiteLocalAddress()) { list.add(address); } } } } if (list.isEmpty()) { throw new IllegalArgumentException("No up-and-running site-local (private) addresses found, got " + getInterfaces()); } return list.toArray(new InetAddress[list.size()]); }
/** * Tries to guess if the network interface is a virtual adapter * by one of the makers of virtualization solutions (e.g. VirtualBox, * VMware, etc). This is by no means a bullet proof method which is * why it errs on the side of caution. * * @param nif network interface * @return */ public static boolean isSoftwareVirtualAdapter(NetworkInterface nif) { try { // VirtualBox uses a semi-random MAC address for their adapter // where the first 3 bytes are always the same: // Windows, Mac OS X, Linux : begins with 0A-00-27 // Solaris: begins with 10-00-27 // (above from VirtualBox source code) // byte[] macAddress = nif.getHardwareAddress(); if (macAddress != null & macAddress.length >= 3) { if ((macAddress[0] == 0x0A || macAddress[0] == 0x08) && (macAddress[1] == 0x00) && (macAddress[2] == 0x27)) { return true; } } return false; } catch (SocketException ex) { return false; } }
/** * 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; } } }
public static boolean addressResolvesToThisNode(InetAddress masterNode) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { throw new RuntimeException( "Failure to retrieve any network interfaces from the node. Check that {} is a valid address and the system can correctly resolve it."); } for (NetworkInterface networkInterface : Collections.list(interfaces)) { Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses(); if (inetAddressEnumeration == null) { continue; } for (InetAddress address : Collections.list(inetAddressEnumeration)) { if (address.equals(masterNode)) { return true; } } } } catch (SocketException e) { throw new RuntimeException( "Failure retrieving all network interfaces from the node. Check that " + masterNode + " is a valid address and the system can correctly resolve it.", e); } return false; }
/** * get local ip address * * @return */ public static String getLocalIpAddress(Context context) { String localIp = ""; 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()) { localIp = inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return localIp; }
private static IPInfo getIPInfo() { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = isIPv4Address(sAddr); if (isIPv4) { IPInfo info = new IPInfo(); info.addr = addr; info.intf = intf; info.ip = sAddr; info.ip_hex = InetAddress_to_hex(addr); info.netmask_hex = netmask_to_hex(intf.getInterfaceAddresses().get(0).getNetworkPrefixLength()); return info; } } } } } catch (SocketException e) { e.printStackTrace(); } return null; }
@Override public void run() { OutputStream outputStream = null; try { outputStream = this.acceptSocket.getOutputStream(); TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress()); while (!this.acceptSocket.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, // we throw our own SocketException // to break the "keep alive" loop above. If // the exception was anything other // than the expected SocketException OR a // SocketTimeoutException, print the // stacktrace if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) { NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e); } } finally { safeClose(outputStream); safeClose(this.inputStream); safeClose(this.acceptSocket); NanoHTTPD.this.asyncRunner.closed(this); } }
@Test public void testVoteSending() throws Exception { try { /* Open up connection to Votifier */ Socket socket = new Socket("127.0.0.1", 8192); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); /* Read Votifier packet and grab challenge token */ String in = new BufferedReader(new InputStreamReader(is)).readLine(); String[] votifierIn = in.split(" "); Assert.assertEquals("Incorrect Votifier data!", 3, votifierIn.length); Assert.assertEquals("Votifier signature mismatch", "VOTIFIER", votifierIn[0]); String challengeToken = votifierIn[2]; /* Create vote object */ Votifier2.Vote vote = Votifier2.newVoteObject(TEST_VOTER_NAME, TEST_SERVICE_NAME); byte[] message = Votifier2.encodeMessage(vote, challengeToken, TEST_SERVER_KEY); /* Send vote object */ os.write(message); os.flush(); /* Read status */ in = new BufferedReader(new InputStreamReader(is)).readLine(); JSONObject result = new JSONObject(in); Assert.assertEquals("Votifier status was not 'ok'! Data: " + result, "ok", result.get("status")); /* Close connection */ os.close(); socket.close(); } catch(SocketException e){ /* Skip test */ Assume.assumeNoException(e); } }
@Test public void testResumeOnRetryWithException() throws Exception { final AtomicBoolean alert = new AtomicBoolean(); final AbstractController controller = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { runnable.run(); } }; final Host host = new Host(new TestProtocol(), "test.cyberduck.ch"); final TransferOptions options = new TransferOptions(); final TransferBackgroundAction action = new TransferBackgroundAction(controller, new DefaultSessionPool( new TestLoginConnectionService(), new DisabledX509TrustManager(), new DefaultX509KeyManager(), new DefaultVaultRegistry(new DisabledPasswordCallback()), PathCache.empty(), new DisabledTranscriptListener(), host) { @Override public Session<?> borrow(final BackgroundActionState callback) throws BackgroundException { throw new ConnectionRefusedException("d", new SocketException()); } }, SessionPool.DISCONNECTED, new TransferAdapter(), new DownloadTransfer(host, Collections.singletonList(new TransferItem(new Path("/home/test", EnumSet.of(Path.Type.file)), new NullLocal("/t")))), options) { @Override public boolean alert(final BackgroundException failure) { final boolean alerted = alert.get(); alert.set(true); return !alerted; } }; assertFalse(alert.get()); // Connect, prepare and run new BackgroundCallable<Boolean>(action, controller, BackgroundActionRegistry.global()).call(); assertTrue(alert.get()); assertTrue(action.hasFailed()); // assertTrue(options.resumeRequested); }
public static boolean isLoopbackAvailable() throws NoSuchFieldException{ try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); if (ni.isLoopback()) { return true; } } } catch (SocketException e) { throw new NoSuchFieldException("Errors occured whilst locating the loopback interface on this machine"); } return false; }
protected void handShake() throws IOException { if( ssl.getWantClientAuth() ) { log.debug("No client cert sent for want"); } else { ssl.setNeedClientAuth(true); } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[0]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if(log.isTraceEnabled()) log.trace("Reading for try #" +i); try { int x = in.read(b); } catch(SSLException sslex) { log.info("SSL Error getting client Certs",sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
private static String createMacAddrString(NetworkInterface netIf) throws SocketException { byte[] macAddr = netIf.getHardwareAddress(); StringBuilder sb = new StringBuilder(); if (macAddr != null) { for (int i = 0; i < macAddr.length; i++) { sb.append(String.format("%02X%s", macAddr[i], (i < macAddr.length - 1) ? "-" : "")); } } return sb.toString(); }
public HttpCodec newCodec( OkHttpClient client, StreamAllocation streamAllocation) throws SocketException { if (http2Connection != null) { return new Http2Codec(client, streamAllocation, http2Connection); } else { socket.setSoTimeout(client.readTimeoutMillis()); source.timeout().timeout(client.readTimeoutMillis(), MILLISECONDS); sink.timeout().timeout(client.writeTimeoutMillis(), MILLISECONDS); return new Http1Codec(client, streamAllocation, source, sink); } }
/** * Parse an adapter name string and return the matching address * * @param adapter String * @return InetAddress * @exception InvalidConfigurationException */ protected final InetAddress parseAdapterName(String adapter) throws InvalidConfigurationException { NetworkInterface ni = null; try { ni = NetworkInterface.getByName( adapter); } catch (SocketException ex) { throw new InvalidConfigurationException( "Invalid adapter name, " + adapter); } if ( ni == null) throw new InvalidConfigurationException( "Invalid network adapter name, " + adapter); // Get the IP address for the adapter InetAddress adapAddr = null; Enumeration<InetAddress> addrEnum = ni.getInetAddresses(); while ( addrEnum.hasMoreElements() && adapAddr == null) { // Get the current address InetAddress addr = addrEnum.nextElement(); if ( IPAddress.isNumericAddress( addr.getHostAddress())) adapAddr = addr; } // Check if we found the IP address to bind to if ( adapAddr == null) throw new InvalidConfigurationException( "Adapter " + adapter + " does not have a valid IP address"); // Return the adapter address return adapAddr; }
@Nullable public static String getSelfIpV4() { try { Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface .getNetworkInterfaces(); if (allNetInterfaces == null) { return null; } while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = allNetInterfaces.nextElement(); if (!netInterface.getName().startsWith("eth")) { continue; } Enumeration<InetAddress> addresses = netInterface .getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { return ip.getHostAddress(); } } } } catch (SocketException e) { logger.error("get sefl IP failed, {}", e); } return null; }
/** * Checks if {@code host} is a local host name and return {@link InetAddress} * corresponding to that address. * * @param host the specified host * @return a valid local {@link InetAddress} or null * @throws SocketException if an I/O error occurs */ public static InetAddress getLocalInetAddress(String host) throws SocketException { if (host == null) { return null; } InetAddress addr = null; try { addr = SecurityUtil.getByName(host); if (NetworkInterface.getByInetAddress(addr) == null) { addr = null; // Not a local address } } catch (UnknownHostException ignore) { } return addr; }
public static String getHostnameOrAddress() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return ""; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address.getHostAddress(); } } interfaces = NetworkInterface.getNetworkInterfaces(); while (addresses.hasMoreElements()) { return addresses.nextElement().getHostAddress(); } return ""; } catch (SocketException e1) { return ""; } } }
@Test public void testDaemonAddressOverrideEnvironmentVariableOverridesSystemProperty() throws SocketException { environmentVariables.set(UDPEmitter.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "1.2.3.4:5"); System.setProperty(UDPEmitter.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "6.7.8.9:10"); UDPEmitter emitter = new UDPEmitter(); InetSocketAddress address = (InetSocketAddress) Whitebox.getInternalState(emitter, "address"); Assert.assertEquals("1.2.3.4", address.getHostString()); Assert.assertEquals(5, address.getPort()); environmentVariables.set(UDPEmitter.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, null); }
protected void setSocketTimeout(int milliseconds) throws SQLException { try { if (this.mysqlConnection != null) { this.mysqlConnection.setSoTimeout(milliseconds); } } catch (SocketException e) { SQLException sqlEx = SQLError.createSQLException("Invalid socket timeout value or state", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); sqlEx.initCause(e); throw sqlEx; } }
public UDPClient() { try { datagramSocket = new DatagramSocket(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static boolean treatAsBindException(SocketException se) { if (se instanceof BindException) { return true; } final String msg = se.getMessage(); return (msg != null && msg.contains("Invalid argument: listen failed")); }