Beispiel #1
0
SOCKET Net_TCPListenPort(int port)
{
	SOCKET				sock = INVALID_SOCKET;
	qbool				error = true;
	struct sockaddr_in	address = {0};
	unsigned long		nonblocking = true;

	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons((u_short)port);

	if ((sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
	{
		// error.
	}
	else if (ioctlsocket (sock, FIONBIO, &nonblocking) == -1)
	{
		// error.
	}
	else if (bind (sock, (void *)&address, sizeof(address)) == -1)
	{
		// error.
	}
	else if (listen(sock, 3) == -1)	// Don't listen for too many clients.
	{
		// error.
	}
	else if (!TCP_Set_KEEPALIVE(sock))
	{
		// error.
	}
	else
	{
		// success.
		error = false;	
	}

	// clean up in casse of error.
	if (error)
	{
		if (sock != INVALID_SOCKET)
		{
			closesocket(sock);
			sock = INVALID_SOCKET;
		}
	}

	return sock;
}
Beispiel #2
0
int TCP_OpenListenSocket (unsigned short int port)
{
	int newsocket;
	struct sockaddr_in address = { 0 };
	unsigned long nonblocking = true;
	int i;

	if ((newsocket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
		Con_Printf ("TCP_OpenListenSocket: socket: (%i): %s\n", qerrno, strerror(qerrno));
		return INVALID_SOCKET;
	}

#ifndef _WIN32
	if ((fcntl (newsocket, F_SETFL, O_NONBLOCK)) == -1) { // O'Rly?! @@@
		Con_Printf ("TCP_OpenListenSocket: fcntl: (%i): %s\n", qerrno, strerror(qerrno));
		closesocket(newsocket);
		return INVALID_SOCKET;
	}
#endif

	if (ioctlsocket (newsocket, FIONBIO, &nonblocking) == -1) { // make asynchronous
		Con_Printf ("TCP_OpenListenSocket: ioctl: (%i): %s\n", qerrno, strerror(qerrno));
		closesocket(newsocket);
		return INVALID_SOCKET;
	}

#ifdef __APPLE__
	address.sin_len = sizeof(address); // apple are special...
#endif
	address.sin_family = AF_INET;

	// check for interface binding option
	if ((i = COM_CheckParm("-ip")) != 0 && i < COM_Argc()) {
		address.sin_addr.s_addr = inet_addr(COM_Argv(i+1));
		Con_DPrintf ("Binding to IP Interface Address of %s\n", inet_ntoa(address.sin_addr));
	}
	else {
		address.sin_addr.s_addr = INADDR_ANY;
	}
	
	if (port == PORT_ANY) {
		address.sin_port = 0;
	}
	else {
		address.sin_port = htons(port);
	}

	if (bind (newsocket, (void *)&address, sizeof(address)) == -1) {
		Con_Printf ("TCP_OpenListenSocket: bind: (%i): %s\n", qerrno, strerror(qerrno));
		closesocket(newsocket);
		return INVALID_SOCKET;
	}

	if (listen (newsocket, TCP_LISTEN_BACKLOG) == INVALID_SOCKET) {
		Con_Printf ("TCP_OpenListenSocket: listen: (%i): %s\n", qerrno, strerror(qerrno));
		closesocket(newsocket);
		return INVALID_SOCKET;
	}

	if (!TCP_Set_KEEPALIVE(newsocket)) {
		Con_Printf ("TCP_OpenListenSocket: TCP_Set_KEEPALIVE: failed\n");
		closesocket(newsocket);
		return INVALID_SOCKET;
	}

	return newsocket;
}