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

x33g5p2x  于2022-01-29 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(114)

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

SocketException介绍

[英]This SocketException may be thrown during socket creation or setting options, and is the superclass of all other socket related exceptions.
[中]此SocketException可能在套接字创建或设置选项期间抛出,它是所有其他与套接字相关的异常的超类。

代码示例

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

@Override
  void dump( Logger logger )
  {
    try
    {
      Enumeration<NetworkInterface> networkInterfaces = getNetworkInterfaces();
      while ( networkInterfaces.hasMoreElements() )
      {
        NetworkInterface iface = networkInterfaces.nextElement();
        logger.log( String.format( "Interface %s:", iface.getDisplayName() ) );
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while ( addresses.hasMoreElements() )
        {
          InetAddress address = addresses.nextElement();
          String hostAddress = address.getHostAddress();
          logger.log( "    address: %s", hostAddress );
        }
      }
    }
    catch ( SocketException e )
    {
      logger.log( "ERROR: failed to inspect network interfaces and addresses: " + e.getMessage() );
    }
  }
},

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

private static InetAddress getIpAddress(AddressSelectionCondition condition) throws
  SocketException {
 // Before we connect somewhere, we cannot be sure about what we'd be bound to; however,
 // we only connect when the message where client ID is, is long constructed. Thus,
 // just use whichever IP address we can find.
 Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
 while (interfaces.hasMoreElements()) {
  NetworkInterface current = interfaces.nextElement();
  if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
  Enumeration<InetAddress> addresses = current.getInetAddresses();
  while (addresses.hasMoreElements()) {
   InetAddress addr = addresses.nextElement();
   if (addr.isLoopbackAddress()) continue;
   if (condition.isAcceptableAddress(addr)) {
    return addr;
   }
  }
 }
 throw new SocketException("Can't get our ip address, interfaces are: " + interfaces);
}

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

public static Collection<InetAddress> getAllAvailableAddresses() {
  Set<InetAddress> retval=new HashSet<>();
  Enumeration en;
  try {
    en=NetworkInterface.getNetworkInterfaces();
    if(en == null)
      return retval;
    while(en.hasMoreElements()) {
      NetworkInterface intf=(NetworkInterface)en.nextElement();
      Enumeration<InetAddress> addrs=intf.getInetAddresses();
      while(addrs.hasMoreElements())
        retval.add(addrs.nextElement());
    }
  }
  catch(SocketException e) {
    e.printStackTrace();
  }
  return retval;
}

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

AnnotatedSocketException(SocketException exception, SocketAddress remoteAddress) {
  super(exception.getMessage() + ": " + remoteAddress);
  initCause(exception);
  setStackTrace(exception.getStackTrace());
}

代码示例来源:origin: Red5/red5-server

Enumeration<NetworkInterface> netInterfaces = null;
try {
  netInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
  e.printStackTrace();
while (netInterfaces.hasMoreElements()) {
  NetworkInterface ni = netInterfaces.nextElement();
  Enumeration<InetAddress> address = ni.getInetAddresses();
  while (address.hasMoreElements()) {
    InetAddress addr = address.nextElement();
    if (addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) {
      return addr.getHostAddress();

代码示例来源:origin: bwssytems/ha-bridge

Enumeration<NetworkInterface> ifs = null;
InetSocketAddress socketAddress = new InetSocketAddress(Configuration.UPNP_MULTICAST_ADDRESS, Configuration.UPNP_DISCOVERY_PORT);
try {
  ifs =    NetworkInterface.getNetworkInterfaces();
}  catch (SocketException e) {
  log.error("Could not get network interfaces for this machine: " + e.getMessage());
  return false;
  while (addrs.hasMoreElements()) {
    if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) {
      if(!useUpnpIface) {
        if(traceupnp)
        IPsPerNic++;
      else if(addr.getHostAddress().equals(responseAddress)) {
        if(traceupnp)
          log.info("Traceupnp: Interface: " + name + " matches upnp config address of IP address: " + addr);
        log.debug("Adding " + name + " to our interface set");
    } catch (IOException e) {
      log.warn("Multicast join failed for: " + socketAddress.getHostName() + " to interface: "
      sendUpnpNotify(socketAddress.getAddress());
      previous = Instant.now();

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

String bindAddress = null;
Enumeration<NetworkInterface> intfs =
  NetworkInterface.getNetworkInterfaces();
while(intfs.hasMoreElements()) {
  NetworkInterface i = intfs.nextElement();
  try {
    if (i.isLoopback()) {
     Enumeration<InetAddress> addrs = i.getInetAddresses();
     while (addrs.hasMoreElements()) {
      InetAddress a = addrs.nextElement();
      if(a.isLoopbackAddress()) {
       bindAddress = a.getHostAddress();
       if (a instanceof Inet6Address) {
         bindAddress = "[" + bindAddress + "]";
    LOG.warn("Couldn't find  loopback interface: " + se.getMessage());
    new InetSocketAddress(bindAddress, PORT), -1);
f.startup(zks);
LOG.info("starting up the the server, waiting");

代码示例来源:origin: bwssytems/ha-bridge

private String checkIpAddress(String ipAddress, boolean checkForLocalhost) {
  Enumeration<NetworkInterface> ifs =    null;
  try {
    ifs =    NetworkInterface.getNetworkInterfaces();
  } catch(SocketException e) {
    log.error("checkIpAddress cannot get ip address of this host, Exiting with message: " + e.getMessage(), e);
    return null;			
  while (ifs.hasMoreElements() && addressString == null) {
    NetworkInterface xface = ifs.nextElement();
    Enumeration<InetAddress> addrs = xface.getInetAddresses();
    String name = xface.getName();
    int IPsPerNic = 0;
    while (addrs.hasMoreElements() && IPsPerNic == 0) {
      address = addrs.nextElement();
      if (InetAddressUtils.isIPv4Address(address.getHostAddress())) {
        log.debug(name + " ... has IPV4 addr " + address);
        if(checkForLocalhost && (!name.equalsIgnoreCase(Configuration.LOOP_BACK_INTERFACE) || !address.getHostAddress().equalsIgnoreCase(Configuration.LOOP_BACK_ADDRESS))) {
          IPsPerNic++;
          addressString = address.getHostAddress();
          log.debug("checkIpAddress found " + addressString + " from interface " + name);

代码示例来源:origin: eclipse/smarthome

private @Nullable String getFirstLocalIPv4Address() {
  try {
    String hostAddress = null;
    final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
      final NetworkInterface current = interfaces.nextElement();
      if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
        continue;
      }
      final Enumeration<InetAddress> addresses = current.getInetAddresses();
      while (addresses.hasMoreElements()) {
        final InetAddress currentAddr = addresses.nextElement();
        if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
          continue;
        }
        if (hostAddress != null) {
          LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
        } else {
          hostAddress = currentAddr.getHostAddress();
        }
      }
    }
    return hostAddress;
  } catch (SocketException ex) {
    LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
    return null;
  }
}

代码示例来源:origin: eclipse/smarthome

/**
 * Get all broadcast addresses on the current host
 *
 * @return list of broadcast addresses, empty list if no broadcast addresses found
 */
public static List<String> getAllBroadcastAddresses() {
  List<String> broadcastAddresses = new LinkedList<String>();
  try {
    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
      final NetworkInterface networkInterface = networkInterfaces.nextElement();
      final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        final InetAddress addr = interfaceAddress.getAddress();
        if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast != null) {
            broadcastAddresses.add(broadcast.getHostAddress());
          }
        }
      }
    }
  } catch (SocketException ex) {
    LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
  }
  return broadcastAddresses;
}

代码示例来源:origin: ac-pm/Inspeckage

public void loadInterfaces(){
  StringBuilder sb = new StringBuilder();
  sb.append("All interfaces,");
  try {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
      NetworkInterface netInterface = en.nextElement();
      for (Enumeration<InetAddress> enumIpAddr = netInterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
        InetAddress inetAddress = enumIpAddr.nextElement();
        String address = inetAddress.getHostAddress();
        boolean isIPv4 = address.indexOf(':') < 0;
        if (isIPv4) {
          sb.append(address+",");
        }
      }
    }
  } catch (SocketException ex) {
    Log.e("Inspeckage_Error", ex.toString());
  }
  SharedPreferences.Editor edit = mPrefs.edit();
  edit.putString(Config.SP_SERVER_INTERFACES, sb.toString().substring(0,sb.length()-1));
  edit.apply();
}
@Override

代码示例来源:origin: sixt/ja-micro

private void updateIpAddress() {
  try {
    Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
    ipAddress = null;
    while( b.hasMoreElements()){
      NetworkInterface iface = b.nextElement();
      if (iface.getName().startsWith("dock")) {
        continue;
      }
      for ( InterfaceAddress f : iface.getInterfaceAddresses()) {
        if (f.getAddress().isSiteLocalAddress()) {
          ipAddress = f.getAddress().getHostAddress();
        }
      }
    }
  } catch (SocketException e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: yuliskov/SmartYouTubeTV

private boolean testIPv4() {
    try {
      Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
      while (networks.hasMoreElements()) {
        NetworkInterface network = networks.nextElement();
        for (InterfaceAddress address : network.getInterfaceAddresses()) {
          if (address.getAddress() instanceof Inet4Address) {
            // found IPv4 address
            // do any other validation of address you may need here
            return true;
          }
        }
      }
      return false;
    } catch (SocketException e) {
      e.printStackTrace();
      throw new IllegalStateException(e);
    }
  }
}

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

private void checkJoinOrLeave(SocketAddress groupAddress, NetworkInterface netInterface) throws IOException {
  checkOpen();
  if (groupAddress == null) {
    throw new IllegalArgumentException("groupAddress == null");
  }
  if (netInterface != null && !netInterface.getInetAddresses().hasMoreElements()) {
    throw new SocketException("No address associated with interface: " + netInterface);
  }
  if (!(groupAddress instanceof InetSocketAddress)) {
    throw new IllegalArgumentException("Group address not an InetSocketAddress: " +
        groupAddress.getClass());
  }
  InetAddress groupAddr = ((InetSocketAddress) groupAddress).getAddress();
  if (groupAddr == null) {
    throw new SocketException("Group address has no address: " + groupAddress);
  }
  if (!groupAddr.isMulticastAddress()) {
    throw new IOException("Not a multicast group: " + groupAddr);
  }
}

代码示例来源:origin: alibaba/TProfiler

public void run() {
  try {
    socket = new ServerSocket(Manager.PORT);
    while (true) {
      Socket child = socket.accept();
      child.setSoTimeout(5000);
      String command = read(child.getInputStream());
        write(child.getOutputStream());
      } else if (Manager.FLUSHMETHOD.equals(command)) {
        MethodCache.flushMethodData();
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();

代码示例来源:origin: qiujuer/Genius-Android

@Override
public void start() {
  Socket socket = null;
  try {
    Long startTime = System.currentTimeMillis();
    socket = new Socket();
    try {
      socket.setSoTimeout(TIME_OUT);
    } catch (SocketException e) {
      e.printStackTrace();
    }
    socket.connect(new InetSocketAddress(mHost, mPort), TIME_OUT);
    if (isConnected = socket.isConnected())
      mDelay = System.currentTimeMillis() - startTime;
    else
      mError = Cmd.TCP_LINK_ERROR;
  } catch (UnknownHostException e) {
    mError = Cmd.UNKNOWN_HOST_ERROR;
  } catch (IOException e) {
    mError = Cmd.TCP_LINK_ERROR;
  } finally {
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

代码示例来源:origin: square/okhttp

socketPort = proxySocketAddress.getPort();
 throw new SocketException("No route to " + socketHost + ":" + socketPort
   + "; port is out of range");
 inetSocketAddresses.add(InetSocketAddress.createUnresolved(socketHost, socketPort));
} else {
 eventListener.dnsStart(call, socketHost);
  inetSocketAddresses.add(new InetSocketAddress(inetAddress, socketPort));

代码示例来源:origin: zstackio/zstack

Socket socket = null;
socket = new Socket();
try {
  socket.setReuseAddress(true);
  SocketAddress sa = new InetSocketAddress(ip, port);
  socket.connect(sa, timeout);
  return socket.isConnected();
} catch (SocketException e) {
  logger.debug(String.format("unable to connect remote port[ip:%s, port:%s], %s", ip, port, e.getMessage()));
  return false;
} catch (IOException e) {

代码示例来源:origin: android-hacker/VirtualXposed

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;
}

代码示例来源:origin: apache/incubator-gobblin

@Override
 void handleClientSocket(Socket clientSocket) throws IOException {
  LOG.info("Writing to client");

  BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  PrintWriter out = new PrintWriter(clientSocket.getOutputStream());

  try {
   out.println("Hello");
   out.flush();

   String line = in.readLine();
   while (line != null && isServerRunning()) {
    out.println(line + " " + line);
    out.flush();
    line = in.readLine();
   }
  }
  catch (SocketException se) {
   // don't bring down server when client disconnected abruptly
   if (!se.getMessage().contains("Connection reset")) {
    throw se;
   }
  }
  finally {
   clientSocket.close();
  }
 }
}

相关文章