コード例 #1
0
ファイル: main.cpp プロジェクト: Guthius/gs2emu-googlecode
void acceptSock(CSocket& pSocket, int pType)
{
	CSocket* newSock = pSocket.accept();
	if (newSock == 0)
		return;

	// Server ip bans.
	if (pType == SOCK_SERVER)
	{
		CString ip(newSock->getRemoteIp());
		for (std::vector<CString>::const_iterator i = ipBans.begin(); i != ipBans.end(); ++i)
		{
			if (ip.match(*i))
			{
				printf("Rejected server: %s matched ip ban %s\n", ip.text(), i->text());
				newSock->disconnect();
				delete newSock;
				return;
			}
		}
	}

	//newSock->setOptions( SOCKET_OPTION_NONBLOCKING );
	serverlog.out(CString() << "New Connection: " << CString(newSock->getRemoteIp()) << " -> " << ((pType == SOCK_PLAYER) ? "Player" : "Server") << "\n");
	if (pType == SOCK_PLAYER || pType == SOCK_PLAYEROLD)
		playerList.push_back(new TPlayer(newSock, (pType == SOCK_PLAYEROLD ? true : false)));
	else serverList.push_back(new TServer(newSock));
}
コード例 #2
0
ファイル: CSocket.cpp プロジェクト: Guthius/gs2emu-googlecode
CSocket* CSocket::accept()
{
	// Make sure the socket is connected!
	if (properties.state == SOCKET_STATE_DISCONNECTED)
		return 0;

	// Only server type TCP sockets can accept new connections.
	if (properties.type != SOCKET_TYPE_SERVER || properties.protocol != SOCKET_PROTOCOL_TCP)
		return 0;

	sockaddr_storage addr;
	int addrlen = sizeof(addr);
	SOCKET handle = 0;

	// Try to accept a new connection.
	handle = ::accept(properties.handle, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
	if (handle == INVALID_SOCKET)
	{
		int error = identifyError();
		if (error == EWOULDBLOCK || error == EINPROGRESS) return 0;
		SLOG("[CSocket::accept] accept() returned error: %s\n", errorMessage(error));
		return 0;
	}

	// Create the new socket to store the new connection.
	CSocket* sock = new CSocket();
	sock_properties props;
	memset((void*)&props, 0, sizeof(sock_properties));
	memset((void*)&properties.address, 0, sizeof(struct sockaddr_storage));
	memcpy((void*)&props.address, &addr, sizeof(addr));
	props.protocol = properties.protocol;
	props.type = SOCKET_TYPE_CLIENT;
	props.state = SOCKET_STATE_CONNECTED;
	props.handle = handle;
	sock->setProperties(props);
	sock->setDescription(sock->getRemoteIp());

	// Disable the nagle algorithm.
	if (props.protocol == SOCKET_PROTOCOL_TCP)
	{
		int nagle = 1;
		setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (char*)&nagle, sizeof(nagle));
	}

	// Set as non-blocking.
#if defined(_WIN32) || defined(_WIN64)
	u_long flags = 1;
	ioctlsocket(handle, FIONBIO, &flags);
#else
	int flags = fcntl(properties.handle, F_GETFL, 0);
	fcntl(handle, F_SETFL, flags | O_NONBLOCK);
#endif

	// Accept the connection by calling getsockopt.
	int type, typeSize = sizeof(int);
	getsockopt(handle, SOL_SOCKET, SO_TYPE, (char*)&type, (socklen_t*)&typeSize);

	return sock;
}