//----------------------------------------------------------------------------
void SocketImpl::Bind6(const SocketAddress& address, bool reuseAddress, 
	bool ipV6Only)
{
#if defined(PX2_HAVE_IPV6)
	if (address.GetFamily() != IPAddress::IPv6)
	{
		assertion(false, "SocketAddress must be an IPv6 address");
	}

	if (mSocket == PX2_INVALID_SOCKET)
	{
		Init(address.GetAF());
	}
#ifdef IPV6_V6ONLY
	SetOption(IPPROTO_IPV6, IPV6_V6ONLY, ipV6Only ? 1 : 0);
#else
	if (ipV6Only)
	{
		assertion(false, "IPV6_V6ONLY not defined.");
	}
#endif
	if (reuseAddress)
	{
		SetReuseAddress(true);
		SetReusePort(true);
	}
	int rc = ::bind(mSocket, address.GetAddr(), address.GetAddrLength());
	if (rc != 0)
	{
		NetError::Error(address.ToString());
	}
#else
	assertion(false, "No IPv6 support available.\n");
#endif
}
//----------------------------------------------------------------------------
void SocketImpl::Bind(const SocketAddress& address, bool reuseAddress)
{
	if (mSocket == PX2_INVALID_SOCKET)
	{
		Init(address.GetAF());
	}

	if (reuseAddress)
	{
		SetReuseAddress(true);
		SetReusePort(true);
	}

	int rc = ::bind(mSocket, address.GetAddr(), address.GetAddrLength());

	if (rc != 0)
	{
		NetError::Error(address.ToString());
	}
}
//----------------------------------------------------------------------------
int SocketImpl::ConnectNB(const SocketAddress& address)
{
	if (mSocket == PX2_INVALID_SOCKET)
	{
		Init(address.GetAF());
	}

	SetBlocking(false);

	int rc = ::connect(mSocket, address.GetAddr(), address.GetAddrLength());

	if (rc != 0)
	{
		int err = NetError::LastError();

		if (err != PX2_EINPROGRESS && err != PX2_EWOULDBLOCK)
		{
			NetError::Error(err, address.ToString());
		}
	}

	return rc;
}
//----------------------------------------------------------------------------
int SocketImpl::ConnectB(const SocketAddress& address,
	const Timespan& timeout)
{
	if (mSocket == PX2_INVALID_SOCKET)
	{
		Init(address.GetAF());
	}

	SetBlocking(false);

	int rc = ::connect(mSocket, address.GetAddr(), address.GetAddrLength());

	if (rc != 0)
	{
		int err = NetError::LastError();

		if (err != PX2_EINPROGRESS && err != PX2_EWOULDBLOCK)
		{
			NetError::Error(err, address.ToString());
		}

		if (!Poll(timeout, SELECT_READ | SELECT_WRITE | SELECT_ERROR))
		{
			assertion(false, "connect timed out:%s", address.ToString());
		}

		err = GetSocketError();
		if (err != 0)
		{
			NetError::Error(err);
		}
	}

	SetBlocking(true);

	return rc;
}
//----------------------------------------------------------------------------
int SocketImpl::ConnectB(const SocketAddress& address)
{
	if (mSocket == PX2_INVALID_SOCKET)
	{
		Init(address.GetAF());
	}

	int rc;
	do
	{
		System::SleepSeconds(0.1f);

		rc = ::connect(mSocket, address.GetAddr(), address.GetAddrLength());

	} while (rc != 0 && NetError::LastError() == PX2_EINTR);

	if (rc != 0)
	{
		int err = NetError::LastError();
		NetError::Error(err, address.ToString());
	}

	return rc;
}