1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
   |  
SOCKET Init_Serveur() {
	SOCKET ListenSocket = INVALID_SOCKET;
	int iResult;
	struct addrinfo hints, *result = NULL;
 
	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;  // Address Format Internet
	hints.ai_socktype = SOCK_STREAM;  //  Provides sequenced, reliable, two-way, connection-based byte streams
	hints.ai_protocol = IPPROTO_TCP;  // Indicates that we will use TCP
	hints.ai_flags = AI_PASSIVE;  // Indicates that the socket will be passive => suitable for bind()
	if (iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result) != GOOD_EXEC) {
		std::cout << "Getaddrinfo failed with error: " << iResult << std::endl;
	}
	else {
		if (ListenSocket = socket(result->ai_family, result->ai_socktype,
			result->ai_protocol) == INVALID_SOCKET) {
			std::cout << "Socket failed with error: " << WSAGetLastError() << std::endl;
			ListenSocket = INVALID_SOCKET;
		}
		else {
			if (iResult = bind(ListenSocket, result->ai_addr,
				(int)result->ai_addrlen) == SOCKET_ERROR) {
				std::cout << "Bind failed with error: " << WSAGetLastError() << std::endl;
				closesocket(ListenSocket);
				ListenSocket = INVALID_SOCKET;
			}
			else {
				if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
					std::cout << "Listen failed with error: " << WSAGetLastError() << std::endl;
					closesocket(ListenSocket);
					ListenSocket = INVALID_SOCKET;
				}
			}
		}
	}		
	freeaddrinfo(result);
 
	return ListenSocket;
} | 
Partager