#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>

/* This is a temporary wrapper to allow this program to function
 * under NTO. When socketpair() is supported under the new NTO TCP/IP
 * remove this file and replace the mysocketpair() call with an
 * identical socketpair() call
 */
#ifdef __QNXNTO__

int mysocketpair(int d, int type, int protocol, int *sv)
{
	int sock, length, fds[2], x;
	struct hostent *hp;
	struct sockaddr_in server;

	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = 0;
	length = sizeof(server);
	sock = fds[0] = fds[1] = -1;

	/* create sockets, ignore what user said to do */
	if (((hp = gethostbyname("127.1")) == NULL) ||
		((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) ||
		((fds[1] = socket(AF_INET, SOCK_STREAM, 0)) == -1) ||
		bind(sock, &server, sizeof(server)) ||
		getsockname(sock, &server, &length) ||
		listen(sock, 5) ||
		((x = fcntl(fds[1], F_GETFL, 0)) == -1) ||
		(fcntl(fds[1], F_SETFL, x | O_NONBLOCK) == -1) ||
		(memcpy(&server.sin_addr, hp->h_addr, hp->h_length), 0) ||
		(connect(fds[1], &server, sizeof(server)) != -1) ||
		(errno != EINPROGRESS) ||
		((fds[0] = accept(sock, (struct sockaddr *)0, (int *)0)) == -1) ||
		((x = fcntl(fds[1], F_GETFL, 0)) == -1) ||
		(fcntl(fds[1], F_SETFL, x & ~O_NONBLOCK) == -1)) {
		x = errno;
		close(sock);
		close(fds[0]);
		close(fds[1]);
		errno = x;
		return -1;
	}

	close(sock);
	sv[0] = fds[0];
	sv[1] = fds[1];
	return 0;
}

#endif
