Пример #1
0
  /**
   * Opens a server TCP connection to clients. Creates, binds, and listens
   *
   * @param port local TCP port to listen on
   * @param backlog listen backlog.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int openServer(int port, int backlog) throws IOException {
    int fd = -1;

    fd = Socket.INSTANCE.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

    set_blocking_flags(fd, /*is_blocking*/ false);

    IntByReference option_val = new IntByReference(1);
    if (sockets.setsockopt(fd, Socket.SOL_SOCKET, Socket.SO_REUSEADDR, option_val, 4) < 0) {
      throw newError(fd, "setSockOpt");
    }
    option_val.free();

    Socket.sockaddr_in local_sin = new Socket.sockaddr_in();
    local_sin.sin_family = Socket.AF_INET;
    local_sin.sin_port = Inet.htons((short) port);
    local_sin.sin_addr = Socket.INADDR_ANY;
    if (sockets.bind(fd, local_sin) < 0) {
      throw newError(fd, "bind");
    }

    if (sockets.listen(fd, backlog) < 0) {
      throw newError(fd, "listen");
    }

    return fd;
  }
Пример #2
0
 /**
  * set a socket option
  *
  * @param socket socket descriptor
  * @param option_name
  * @param option_value new value
  * @throws IOException on error
  */
 public void setSockOpt(int socket, int option_name, int option_value) throws IOException {
   IntByReference value = new IntByReference(option_value);
   int err = sockets.setsockopt(socket, Socket.SOL_SOCKET, option_name, value, 4);
   value.free();
   LibCUtil.errCheckNeg(err);
 }