}
-/**
- * Initialize a struct sockaddr_in.
- *
- * \param addr A pointer to the struct to be initialized.
- * \param port The port number to use.
- * \param he The address to use.
- *
- * If \a he is null (server mode), \a addr->sin_addr is initialized with \p
- * INADDR_ANY. Otherwise, the address given by \a he is copied to addr.
- */
-static void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
-{
- /* host byte order */
- addr->sin_family = AF_INET;
- /* short, network byte order */
- addr->sin_port = htons(port);
- if (he)
- addr->sin_addr = *((struct in_addr *)he->h_addr);
- else
- addr->sin_addr.s_addr = INADDR_ANY;
- /* zero the rest of the struct */
- memset(&addr->sin_zero, '\0', 8);
-}
-
/**
* Determine the socket type for a given layer-4 protocol.
*
return n;
}
-/**
- * Establish a tcp connection.
- *
- * \param host Hostname or IPv4 address.
- * \param port The tcp port.
- *
- * \return Negative on errors, a valid file descriptor on success.
- */
-int tcp_connect(char *host, int port)
-{
- struct sockaddr_in addr;
- struct hostent *he;
- int ret, fd;
-
- PARA_INFO_LOG("getting host info of %s\n", host);
- /* FIXME: gethostbyname() is obsolete */
- he = gethostbyname(host);
- if (!he)
- return -ERRNO_TO_PARA_ERROR(h_errno);
- init_sockaddr(&addr, port, he);
- ret = get_stream_socket(AF_INET);
- if (ret < 0)
- return ret;
- fd = ret;
- ret = PARA_CONNECT(fd, &addr);
- if (ret >= 0)
- return fd;
- close(fd);
- return ret;
-}
-
/**
* A wrapper around socket(2).
*
}
#endif /* HAVE_UCRED */
-/**
- * Create a tcp socket, bind it and listen on the given port.
- *
- * \param port The tcp port to listen on.
- *
- * \return The file descriptor of the created socket, negative on errors.
- *
- * \sa get_stream_socket()
- * \sa setsockopt(2)
- * \sa bind(2)
- * \sa listen(2)
- */
-int tcp_listen(int port)
-{
- struct sockaddr_in my_addr;
- int fd, ret = get_stream_socket(AF_INET);
-
- if (ret < 0)
- return ret;
- fd = ret;
- ret = 1;
- ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(int));
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- goto err;
- }
- init_sockaddr(&my_addr, port, NULL);
- ret = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- goto err;
- }
- ret = listen(fd, BACKLOG);
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- goto err;
- }
- PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
- return fd;
-err:
- close(fd);
- return ret;
-}
-
/**
* receive a buffer and check for a pattern
*