Java Code Examples for java.net.SocketException#printStackTrace()

The following examples show how to use java.net.SocketException#printStackTrace() . 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: DeviceUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
private static InetAddress getInetAddress() {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            // To prevent phone of xiaomi return "10.0.2.15"
            if (!ni.isUp()) continue;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress inetAddress = addresses.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String hostAddress = inetAddress.getHostAddress();
                    if (hostAddress.indexOf(':') < 0) return inetAddress;
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 2
Source File: IpUtil.java    From AndroidUtils with The Unlicense 6 votes vote down vote up
public static InetAddress getWiFiIpAddress() {
    try {
        for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
            NetworkInterface netI = enNetI.nextElement();
            if (netI.getDisplayName().equals("wlan0") || netI.getDisplayName().equals("eth0")) {
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress;
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: IPUtil.java    From s2g-zuul with MIT License 6 votes vote down vote up
public static String getLinuxLocalIP() {
	String ip = "";
	try {
		Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
		while (e1.hasMoreElements()) {
			NetworkInterface ni = e1.nextElement();
			if ((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 4
Source File: LocalIPUtil.java    From DanDanPlayForAndroid with MIT License 6 votes vote down vote up
private String findLocalIp3(){
    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))
                {
                    return inetAddress.getHostAddress();
                }
            }
        }
    }
    catch (SocketException ex){
        ex.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: NetworkUtil.java    From MvpRxJavaRetrofitOkhttp with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: NetworkUtils.java    From gank with GNU General Public License v3.0 6 votes vote down vote up
public static String getIpAddress() {
    try {
        Enumeration en = NetworkInterface.getNetworkInterfaces();

        while(en.hasMoreElements()) {
            NetworkInterface ex = (NetworkInterface)en.nextElement();
            Enumeration enumIpAddr = ex.getInetAddresses();

            while(enumIpAddr.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                if(!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }

        return null;
    } catch (SocketException var4) {
        var4.printStackTrace();
        return null;
    }
}
 
Example 7
Source File: NetworkUtil.java    From Retrofit2RxjavaDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 得到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;
}
 
Example 8
Source File: ProxyUtils.java    From zongtui-webcrawler with GNU General Public License v2.0 6 votes vote down vote up
private static String getNetworkInterface() {

		String networkInterfaceName = ">>>> modify networkInterface in us.codecraft.webmagic.utils.ProxyUtils";
		Enumeration<NetworkInterface> enumeration = null;
		try {
			enumeration = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e1) {
			e1.printStackTrace();
		}
		while (enumeration.hasMoreElements()) {
			NetworkInterface networkInterface = enumeration.nextElement();

			Enumeration<InetAddress> addr = networkInterface.getInetAddresses();
			while (addr.hasMoreElements()) {
				String s = addr.nextElement().getHostAddress();
				Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
				if (s != null && IPV4_PATTERN.matcher(s).matches()) {
					networkInterfaceName += networkInterface.toString() + "IP:" + s + "\n\n";
				}
			}
		}
		return networkInterfaceName;
	}
 
Example 9
Source File: WifiUtils.java    From WifiChat with GNU General Public License v2.0 6 votes vote down vote up
public static String getGPRSLocalIPAddress() {
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nif = en.nextElement();
            Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress mInetAddress = enumIpAddr.nextElement();
                if (!mInetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(mInetAddress.getHostAddress())) {
                    return mInetAddress.getHostAddress();
                }
            }
        }
    }
    catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 10
Source File: UdpConnectThread.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public void run() {
    super.run();
    while (!this.isExit) {
        try {
            if (!SessionManager.getInstance().hasSession()) {
                try {
                    UdpConnect udpConnect = new UdpConnect(new DatagramSocket(), this.option, new DataChanel());
                    udpConnect.startSession();
                    SessionManager.getInstance().addSession(udpConnect);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        } catch (SocketException e2) {
            e2.printStackTrace();
        }
    }
}
 
Example 11
Source File: Fix5070632.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 12
Source File: SpActivity.java    From MvpRoute with Apache License 2.0 5 votes vote down vote up
public static String getIPAddress(Context context) {
	NetworkInfo info = ((ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
	if (info != null && info.isConnected()) {
		if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
			try {
				//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
				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) {
							return inetAddress.getHostAddress();
						}
					}
				}
			} catch (SocketException e) {
				e.printStackTrace();
			}

		} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
			return ipAddress;
		}
	} else {
	}
	return "获取失败";
}
 
Example 13
Source File: Fix5070632.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 14
Source File: SerialPortFactoryTcpServer.java    From jlibmodbus with Apache License 2.0 5 votes vote down vote up
public void setReadTimeout(int readTimeout) {
    setTimeout(readTimeout);

    synchronized (this) {
        if (isOpened()) {
            super.setReadTimeout(readTimeout);
            try {
                client.setSoTimeout(readTimeout);
            } catch (SocketException e) {
                e.printStackTrace();
                Modbus.log().warning("Unable to set readTimeout: " + e.getLocalizedMessage());
            }
        }
    }
}
 
Example 15
Source File: Fix5070632.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 16
Source File: WifiDelegate.java    From wifi with MIT License 5 votes vote down vote up
private void launchIP() {
    NetworkInfo info = ((ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            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) {
                            result.success(inetAddress.getHostAddress());
                            clearMethodCallAndResult();
                        }
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
            result.success(ipAddress);
            clearMethodCallAndResult();
        }
    } else {
        finishWithError("unavailable", "ip not available.");
    }
}
 
Example 17
Source File: LinuxSeries.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public String getSeries() {
//		try {
////			NativeInterfaces.setLibDir(new File("lib"));
//			NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() 
//					+ File.separator + System.getProperty("sun.arch.data.model")));
//			EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
//			String series = "";
//			for (EthernetAddress a : macs) {
//				series += a.toString() + "+";
//			}
//			return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}	
		
		try {
			String series = "";
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface network = networkInterfaces.nextElement();
				if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
					byte[] mac = network.getHardwareAddress();
					if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02x", mac[i]));
						}
						sb.append("+");
						series += sb.toString();
					}
				}
			}
			return "".equals(series) ? null : series.substring(0, series.length() - 1);
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
 
Example 18
Source File: ModbusTCPListener.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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
    }
}
 
Example 19
Source File: NetworkUtils.java    From AcgClub with MIT License 5 votes vote down vote up
/**
 * Return the ip address.
 * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
 *
 * @param useIPv4 True to use ipv4, false otherwise.
 * @return the ip address
 */
@RequiresPermission(INTERNET)
public static String getIPAddress(final boolean useIPv4) {
  try {
    Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    while (nis.hasMoreElements()) {
      NetworkInterface ni = nis.nextElement();
      // To prevent phone of xiaomi return "10.0.2.15"
      if (!ni.isUp()) {
        continue;
      }
      Enumeration<InetAddress> addresses = ni.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress inetAddress = addresses.nextElement();
        if (!inetAddress.isLoopbackAddress()) {
          String hostAddress = inetAddress.getHostAddress();
          boolean isIPv4 = hostAddress.indexOf(':') < 0;
          if (useIPv4) {
            if (isIPv4) {
              return hostAddress;
            }
          } else {
            if (!isIPv4) {
              int index = hostAddress.indexOf('%');
              return index < 0
                  ? hostAddress.toUpperCase()
                  : hostAddress.substring(0, index).toUpperCase();
            }
          }
        }
      }
    }
  } catch (SocketException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 20
Source File: SocketProxy.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public Acceptor(ServerSocket serverSocket, URI uri) {
   socket = serverSocket;
   target = uri;
   pause.set(new CountDownLatch(0));
   try {
      socket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS);
   } catch (SocketException e) {
      e.printStackTrace();
   }
}