Ejemplo n.º 1
0
  /** @inheritDoc */
  public int open(String hostname, int port, int mode) throws IOException {
    // init_sockets(); win32 only
    int fd = -1;

    fd = sockets.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (DEBUG) {
      System.err.println("Socket.socket() = " + fd);
    }
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

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

    NetDB.hostent phostent;
    // hostname is always NUL terminated. See socket/Protocol.java for detail.
    phostent = NetDB.INSTANCE.gethostbyname(hostname);
    if (phostent == null) {
      throw newError(fd, "gethostbyname (herrono = " + NetDB.INSTANCE.h_errno() + ")");
    }

    Socket.sockaddr_in destination_sin = new Socket.sockaddr_in();
    destination_sin.sin_family = Socket.AF_INET;
    destination_sin.sin_port = Inet.htons((short) port);
    destination_sin.sin_addr = phostent.h_addr_list[0];

    if (DEBUG) {
      System.err.println("Socket.sockaddr_in: " + destination_sin);
      System.err.println("connect: hostname: " + hostname + " port: " + port + " mode: " + mode);
    }
    if (sockets.connect(fd, destination_sin, destination_sin.size()) < 0) {
      int err_code = LibCUtil.errno();
      if (err_code == LibC.EINPROGRESS || err_code == LibC.EWOULDBLOCK) {
        // When the socket is ready for connect, it becomes *writable*
        // (according to BSD socket spec of select())
        VMThread.getSystemEvents().waitForWriteEvent(fd);
      } else {
        throw newError(fd, "connect");
      }
    }

    return fd;
  }