Пример #1
0
int main(int argc, char *argv[])
{
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
				
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    else if (WSAGetLastError() != WSAETIMEDOUT)
                    {
                        //printf("ERROR waiting\n");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx]) < 0)
                        {
							printf("Disconnecting...\n");
							disconnect_socket(&sockets[idx]);
							sockets[idx] = sockets[opened_sockets-1];
							sockets[opened_sockets-1] = INVALID_SOCKET;
							opened_sockets--;
                        }
                    }
                }
            }
        }
        else
        {
            perror("ERROR binding");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        perror("ERROR opening socket");
    }

    destroy_socket(&sockfd);

    return 0;
}
Пример #2
0
int main(int argc, char *argv[])
{
	WSADATA wsaData;
	  // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    //else if (errno != WSAETIMEDOUT)
                    {
                        //puts("ERROR waiting");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx])==-1)
                        {
                            if (errno != WSAETIMEDOUT)
                            {
                                printf("Disconnecting...\n");
                                disconnect_socket(&sockets[idx]);
                                sockets[idx] = sockets[opened_sockets-1];
                                sockets[opened_sockets-1] = INVALID_SOCKET;
                                opened_sockets--;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            printf("ERROR binding\n");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        printf("ERROR opening socket\n");
    }

    destroy_socket(&sockfd);

    return 0;
}
int main(int argc, char *argv[])
{
	int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char s[INET6_ADDRSTRLEN];
	int rv;
	int pid;

	int bytes_sent, bytes_rcvd;

        struct sockaddr_storage remoteaddr; // client address
        socklen_t addrlen, to_len;
	//file variables
	FILE *fp;
	long int file_size;

    //dir variables
	DIR *mydir;
	char dirbuffer[MAX_BUF_SIZE];
	char buffer[MAX_BUF_SIZE];
	struct dirent *mydirentp;
	
	char in_opt;
	int dir_flag = 0, select_flag = 0; //input handle flags

    //select variables
	fd_set master;		//master file descriptor
	fd_set readfds;		//temp file descriptor list for select()
	int fdmax;		//maximum file descriptor number
	int i, j;
	char remoteIP[INET6_ADDRSTRLEN];

    //udp handle
	int udp_flag = 0;
	typedef struct clientStruct
	{
		int client_id;
		char ip[INET6_ADDRSTRLEN];
		char dir[MAX_BUF_SIZE];
		
	}clientStruct;	

	clientStruct clients[MAX_CLIENT_CONNECTION];
	int clientIndex = 0;
	to_len = sizeof(struct sockaddr_storage);
	socklen_t from_len = sizeof their_addr;
	

	for (i = 0; i < MAX_CLIENT_CONNECTION; i++)
	{
		bzero((clients[i]).dir, MAX_BUF_SIZE);
		strcpy(clients[i].dir, "/");
		clients[i].client_id = -1;
	}

	while(1)
	{
		in_opt = getopt(argc, argv, "usd:");
		if (in_opt == -1) //we finished processing all the arguments 
		{
			break;
		}
	
		switch(in_opt)
		{
			case 'd':
			{
				printf("User invoked -d %s \n", optarg);
				if (chdir (optarg) != 0)
				{
					printf("Invalid directory given, please try again\n");
					exit(1);

				}
				else
				{
					if (getcwd(buffer, sizeof buffer) != NULL)
					{
						printf("Setting default dir to: %s\n\n", optarg);
						dir_flag = 1;
					
					    //set the -d path as defualt directory for incoming users
						for (i = 0; i < MAX_CLIENT_CONNECTION; i++)
						{
							bzero((clients[i]).dir, MAX_BUF_SIZE);
							strcpy(clients[i].dir, optarg);
						}		
					}
				}
				break;
			}
			case 's':
			{
				printf("Select will be used instead of forking:\n");
				select_flag = 1;
				break;
			}
			case 'u':
			{
				printf("Ok, I will accept connections in UDP:\n");
				udp_flag = 1;
				break;
			}
			case '?':
			{
				printf("An unfarmilier handle type char inserted\n");
				break;
			}
			default:
			{
				printf("No opt char inserted\n");
			}
		}
	}

    //computition
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_flags = AI_PASSIVE; // use my IP
	
	if (udp_flag == 0)
	{
		hints.ai_socktype = SOCK_STREAM;
	}
	else //UDP-server mode selected
	{
		hints.ai_socktype = SOCK_DGRAM;
	}
	

	if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

    //loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next)
	{
		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
		{
			perror("server: socket");
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) 
		{
			perror("setsockopt");
			exit(1);
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
		{
			close(sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	if (p == NULL)
	{
		fprintf(stderr, "server: failed to bind\n");
		return 2;
	}

	freeaddrinfo(servinfo); // all done with this structure

   //select handle
	if (select_flag == 0)
	{
		if ((udp_flag == 0) && (listen(sockfd, BACKLOG) == -1)) 
		{ //not select depedented
			perror("listen");
			exit(1);
		}
		sa.sa_handler = sigchld_handler; // reap all dead processes
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_RESTART;
		if (sigaction(SIGCHLD, &sa, NULL) == -1)
		{
			perror("sigaction");
			exit(1);
		}
		if (udp_flag == 0)
		{
			printf("server: waiting for connections...\n");
		}
	}
	else //select dependent
	{
		FD_ZERO(&master);
		FD_ZERO(&readfds);
		if (listen(sockfd, BACKLOG) == -1)
		{
			printf("Error here!\n");
			perror("listen");
			exit(2);
		}
		FD_SET(sockfd, &master);
		fdmax = sockfd; //up until now, this is the max
	}



   //handle [non -d] directive
	if ((dir_flag == 0) && (chdir("/") != 0))
	{
		printf("Error: I couldn't allocate you with the '/' directory\n");
	}
	
	char tempbuffer[MAX_BUF_SIZE];
	if (getcwd(tempbuffer, sizeof tempbuffer) != NULL)
	{
		printf("Current dir is: %s\n", tempbuffer);
	}


	
	while(1) 
	{// main accept() loop
		if (select_flag == 0)
		{
			sin_size = sizeof their_addr;
			if (udp_flag == 0) //tcp connection
			{
			 	new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
				if (new_fd == -1)
				{
					perror("accept");
					continue;
				}

				inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s,
													   sizeof s);
				printf("server: got connection from %s\n", s);

				/*create child process */
				pid = fork();
				if (pid < 0)
				{
					perror("Error on fork");
					exit(1);
				}
				if (pid == 0)
				{
					/*this is the client process*/
					while(1)
					{
						do_processing(new_fd, 0, select_flag, their_addr, 0, tempbuffer,
							   	clients[clientIndex].dir, &clientIndex, &master);
					}
				}
				else
				{
					close(new_fd);
				}
			}

		//----------------------- Start HANDLE UDP CONNECTION -----------------
		  	 else if (udp_flag == 1) //udp_flag == 1
			 {	
			   int ID;		
				bzero(&their_addr, from_len);

				bytes_rcvd = recvfrom(sockfd, tempbuffer, MAX_BUF_SIZE, 0, 
							(struct sockaddr*)&their_addr, &from_len);
				tempbuffer[bytes_rcvd] = '\0';		

			 //place the senders IP as a string on string s
				inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s,
													   sizeof s);
				if (bytes_rcvd == -1)
				{
					perror(NULL);
				}
				
				printf("I Recieved %s from IP: %s\n", tempbuffer, s);

				//check if this is a new connection
				int g, newConnectionFlag = 0;
				for (g = 0; g < MAX_CLIENT_CONNECTION; g++)
				{
					if (strcmp("handeshake", tempbuffer) == 0)
 					{ //meaning this ip is a new client
						newConnectionFlag = 1;
						
					   //send the new client his ID key
						bytes_sent = sendto(sockfd, &clientIndex, sizeof clientIndex, 0, 										(struct sockaddr*)&their_addr, to_len);
						if (bytes_sent == -1)
						{
							perror(NULL);
						}
						break; //end-for 
					}
					else
					{
						newConnectionFlag = 0;
					}
				}
				
				if (newConnectionFlag == 0) //meaning a known-connection
				{
			        //recieve client ID 
					bytes_rcvd = recvfrom(sockfd, &ID, sizeof ID, 0, 
							(struct sockaddr*)&their_addr, &from_len);
					do_processing(sockfd, udp_flag, select_flag, their_addr, 0, tempbuffer, 
									clients[ID].dir, &clientIndex, &master);
				}
				else if (newConnectionFlag == 1)
				{ //we found a new client!

				        strcpy(clients[clientIndex].ip, s);

					//We made an "handeshake" between the client-server already, now lets
					//get to buissness, get command from client
					printf("new connection!\n");
					do_processing(sockfd, udp_flag, select_flag, their_addr, 1, tempbuffer, 
							clients[clientIndex].dir, &clientIndex, &master); //handle request
					clientIndex++;  //increase the client's index (active clients)
				}
			 }
		     }
		//------------------------- END HANDLE UDP CONNECTION -----------------


		//--------------------------Handle -s (select instead of fork) option ---------
		else if (select_flag == 1) 
		{
			readfds = master;  //copy master
			if (select(fdmax+1, &readfds, NULL, NULL, NULL) == -1)
			{
				perror("select");
				exit(3);
			}
			// run through the existing connections looking for data to read
			for(i = 0; i <= fdmax; i++)
			{
			    if (FD_ISSET(i, &readfds)) 
			    { // we got one!!
				if (i == sockfd)
			        {
				    // handle new connections
				    addrlen = sizeof remoteaddr;
				    new_fd = accept(sockfd, (struct sockaddr *)&remoteaddr, &addrlen);

				    if (new_fd == -1) 
				    {
				        perror("accept");
				    }
				    else
				    {
				    	clients[clientIndex].client_id = new_fd;
			    		clientIndex++;					
				        FD_SET(new_fd, &master); // add to master set
				        if (new_fd > fdmax)     // keep track of the max
					{
				            fdmax = new_fd;
				        }
				        printf("selectserver: new connection from %s on socket %d\n",
					       inet_ntop(remoteaddr.ss_family,
				               get_in_addr((struct sockaddr*)&remoteaddr),
				               remoteIP, INET6_ADDRSTRLEN),new_fd);
				    }
				}
				else
				{
					//find the relevant user and get his cwd (clients[j].dir)
					int j;
					for (j = 0; j <= fdmax; j++)
					{
						if (i == clients[j].client_id)
						{
							break;
						}
					}

					do_processing(i, udp_flag, select_flag, their_addr, 0, tempbuffer, 
									clients[j].dir, &clientIndex, &master);
				} // END handle data from client
			    } // END got new incoming connection
			} // END looping through file descriptors
		     // END for(;;)
		}
	}//end while loop
}//end main		
Пример #4
0
int main(int argc, char *argv[])
{
    SOCKET sock = create_socket(), sockets[MAX_CLIENT] = {INVALID_SOCKET};
	int num_clients = 0;
	
	//cria e conecta o socket
	if(sock != INVALID_SOCKET)
    {
        if(bind_socket(&sock, PORT_NO) == SOCKET_ERROR)
		{
			printf("ERROR binding\n");
			exit(1);
		}
            
		else
		{
			listen(sock, MAX_CLIENT);
			printf("Servidor iniciado.\n");
		}
    }
    else
	{
		printf("ERROR opening socket");
		exit(1);
	}
	
	//aceita conexões
	
	puts("Esperando por conexoes...");
	
	while (1)
	{
		int i, max;
		if (num_clients < MAX_CLIENT)
		{
			SOCKET new_sockfd = wait_connection(&sock);

			if(new_sockfd != INVALID_SOCKET)
			{
				sockets[num_clients++] = new_sockfd;
			}
			else if (WSAGetLastError() != WSAETIMEDOUT)
			{
				printf("ERROR waiting\n");
			}
		}

		for (i = 0, max = num_clients; i < max; i++)
		{
			if (sockets[i] != INVALID_SOCKET)
			{
				if (!do_processing(&sockets[i]))
				{
					if (WSAGetLastError() != WSAETIMEDOUT)
					{
						printf("Disconnecting...\n");
						disconnect_socket(&sockets[i]);
						sockets[i] = sockets[num_clients-1];
						sockets[num_clients-1] = INVALID_SOCKET;
						num_clients--;
					}
				}
			}
		}
	}
	
	disconnect_socket(&sock);
    destroy_socket(&sock);

    return 0;
}