Esempio n. 1
0
// Thread which handle the sending of a file
void* handle_send_file(void* pdata)
{
	int sock;
	struct sockaddr_in serv_info;
	char ip[16];
	char port[6];
	char filepath[MSG_BUFFER];
	int c, i;
	FILE* file;
	char bufout[RW_BUFFER];
	struct info* pinfo = pdata;
	ssize_t r,n,t;

	regex_get_filere(pinfo->inbuf, ip, port, filepath);

	// todo erno
	file = fopen(filepath, "rb");

	if(file == NULL)
	{
		printf("\n> Error : file does not exist\n> ");
		fflush(stdout);
		return NULL;
	}
	get_addr_info(&serv_info, ip, port);
	sock = do_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	for(i = 0; i < 5; i++) {
		c = connect(sock, (struct sockaddr*)&serv_info, sizeof(serv_info));
		if(c == 0)
			break;
		sleep(1);
	}

	if(c != 0)
	{
		printf("\n> Cannot connect to client\n> ");
		fflush(stdout);
		fclose(file);
		close(sock);
		return NULL;
	}

	// Send the file
	do {
		t = fread(bufout, 1, RW_BUFFER, file);
		r = t;
		do {
			n = write(sock, bufout, r);
			if (n < 0 )	error("ERROR with write() in do_write()");
			r -= n;
		} while (r > 0);
	} while(t == RW_BUFFER);

	printf("\n> File transfered.\n> ");
	fflush(stdout);

	fclose(file);
	close(sock);
}
Esempio n. 2
0
void Socket::create_and_connect()
{
    addrinfo* serverinfo;
    int res;

    if ((res = get_addr_info(&serverinfo)) != 0)
    {
        throw std::system_error(errno, std::system_category(),
                                REPORT_ERROR("getaddrinfo failure: " +
                                std::string(gai_strerror(res))));
    }

    try
    {
        create_socket(serverinfo);
        connect_socket(serverinfo);
    }
    catch (std::system_error const& err)
    {
        freeaddrinfo(serverinfo);
        close(sock);
        throw err;
    }

    freeaddrinfo(serverinfo);

    if (!server_info.password.empty())
        send_to_socket("PASS " + server_info.password + "\r\n");

    send_to_socket("NICK " + server_info.nick + "\r\n");
    send_to_socket("USER " + server_info.user + "\r\n");
}
Esempio n. 3
0
int main(int argc, char** argv) {
	int quit = 0;

	if (argc != 3) {
		fprintf(stderr, "usage: RE216_CLIENT hostname port\n");
		return 1;
	}

//get address info from the server
//get_addr_info()
	struct addrinfo addr;
	struct addrinfo * add = &addr;
	struct addrinfo ** ad = &add;

	ad = get_addr_info(argv[1], argv[2], ad);

	add = *ad;
	addr = *add;

//get the socket
	int s;
	s = do_socket();

//connect to remote socket
	do_connect(s, addr.ai_addr, addr.ai_addrlen);

	char * buffer = malloc(MAXLEN);
	memset(buffer, 0, MAXLEN);

	for(;;) {
		//get user input
		readline(0, buffer, MAXLEN);

		//send message to the server
		handle_client_message(s, buffer);

		// Test if log off signal was sent
		if (strcmp(buffer, "/quit\n") == 0) {
			fprintf(stderr, "Quit signal sent\n");
			break;
		}
		// Receive an echo and display it
		memset(buffer, 0, MAXLEN);
		read(s, buffer, 256);
		fprintf(stderr, "--> %s", buffer);
	}

	//Clean buffer
	free(buffer);
	//clean up socket
	shutdown(s, SHUT_RDWR);
	close(s);

	return 0;
}
Esempio n. 4
0
int main(int argc,char** argv)
{


    if (argc != 3)
    {
        fprintf(stderr,"usage: RE216_CLIENT hostname port\n");
        return 1;
    }

//get address info from the server
    struct addrinfo addr;
    struct addrinfo * add = &addr;
    struct addrinfo ** res = &add;
    int sockfd;

	get_addr_info(argv[1], argv[2], res);
	add = *res;
	addr= *add;

	//get the socket
	sockfd = do_socket();

	//connect to remote socket
	do_connect(sockfd,addr.ai_addr, addr.ai_addrlen);

    for(;;){
    	char buffer[256];
    	memset(&buffer, 0, 256);

        fprintf (stdout,"Tapez le message à envoyer (moins de 256 caractères) : \n");
        fgets((char *) buffer, 256, stdin);
        int ecrit = write(sockfd, buffer, strlen((char *) buffer));
    	
    	//handle_client_message(sockfd, &buffer, (int) 256);

        memset(&buffer, 0, (int) 256);
        read(sockfd, buffer, (int) 256);
        fprintf(stderr, "SERVER --> %s", buffer);
        if(strcmp(buffer, "Connexion terminée\n") == 0)
            break;
    }

    close(sockfd);


    return 0;


}
Esempio n. 5
0
/* Prepare Ipv6 Socket */
bool prepare_sock6(struct sockaddr_in6 * tgt_addr6)
{
	struct addrinfo *addr_info;
	memset(tgt_addr6, 0, sizeof(*tgt_addr6));

	if ((addr_info = get_addr_info(IPV6)) == NULL) {
		errlog("Erorr: Unable to get address info\n");
		return false;
	}

	tgt_addr6->sin6_addr = ((struct sockaddr_in6 *)addr_info->ai_addr)->sin6_addr;
	tgt_addr6->sin6_port = htons(port);
	tgt_addr6->sin6_family = AF_INET6;

	return true;
}
Esempio n. 6
0
/* Prepare Ipv4 Socket */
bool prepare_sock(struct sockaddr_in * tgt_addr)
{
	struct addrinfo *addr_info;
	memset(tgt_addr, 0, sizeof(*tgt_addr));

	if ((addr_info = get_addr_info(IPV4)) == NULL) {
		errlog("Error: Unable to get address info\n");
		return false;
	}

	tgt_addr->sin_addr = ((struct sockaddr_in *)addr_info->ai_addr)->sin_addr;
	tgt_addr->sin_port = htons(port);
	tgt_addr->sin_family = AF_INET;

	return true;
}
Esempio n. 7
0
void proto_connect() {
	{
		struct addrinfo *info = get_addr_info(bot->host, bot->port);

		bot->socket = getsock(info);
		fcntl(bot->socket, F_SETFL, O_NONBLOCK);
		bot->running = 1;

		// we won't need this anymore.
		freeaddrinfo(info);
	}

	printf("[irc\tinfo] registering with the server.\n");
	sockprintf(bot->socket, "NICK %s", bot->nick);
	sockprintf(bot->socket, "USER apollo * * :hi i'm apollo");
}
Esempio n. 8
0
int main(int argc,char** argv) {

    if (argc != 3) {
        fprintf(stderr,"usage: RE216_CLIENT hostname port\n");
        return 1;
    }
    
	// -----------------------------------------------------------------
	// ------------------------ Variables ------------------------------
	
	// Buffer
	char *input = NULL;		// Taille d'entrée dynamique
	char output[TAILLE_MSG];// Taille de réception fixée
    
	// Liste chaînée pour l'envoi de fichiers
	struct file fichiers;
		memset(&fichiers, 0, sizeof(struct file));

	// Récupération de la structure sockaddr_in6 pour l'adresse du serveur
	struct sockaddr_in6* server_add = get_addr_info(atoi(argv[2]), argv[1]);

	// Création de la socket
	int sckt = do_socket();  

	// Connexion de la socket à l'adresse server_add
	int conn = do_connect(sckt, *server_add);

	// Initialisation des tableaux pour utliser select ------------------
    
    fd_set fd_set_read; // Ici seront stockés les descripteurs de fichier
    
    int i, select_ret_val;
    
    // Socket du serveur quand elle existe
    int socket_fichier = -1;
    
    // Eventuellement : timeout du select
	//~ struct timeval tv;
	//~ tv.tv_sec = 5;
	//~ tv.tv_usec = 0;
	
	init_reg();
	// -----------------------------------------------------------------
	// -----------------------------------------------------------------
	
	start_line();

	// Boucle jusqu'à recevoir le "/quit" final
	do {
		
		// ------------------------ R.A.Z ------------------------------
		// clean the set before adding file descriptors
		FD_ZERO(&fd_set_read);
		
		// add the fd for server connection
		FD_SET(sckt, &fd_set_read);

		// add the fd for user-input
		FD_SET(fileno(stdin), &fd_set_read);
		// -------------------------------------------------------------
		 
		// we now wait for any file descriptor to be available for reading
        select_ret_val = select(sckt + 1, &fd_set_read, NULL, NULL, NULL);//&tv);
        
        if (select_ret_val == -1) {
			error("Erreur concernant le select ");
		}
        
        //printf("Le retour de la fonction select est : %i", select_ret_val);
		
		for (i = 0; i < (sckt+1) && select_ret_val > 0; i++) {
	
            // Le buffer est nettoyé avec memset directement dans les fonctions
            
            //printf("Bonjour je suis le i n°%i. Retour => %i\n", i, select_ret_val);

            // Si le file descripteur i est dans le set mis en écoute, c'est qu'il y a une activité
            if (FD_ISSET(i, &fd_set_read)) {
				
				// printf("Descripteur trouvé : %i\n", i);

                if (i == fileno(stdin)) // C'est une entrée utilisateur
					client_write(&input, sckt, &fichiers);
				
				else // Les données viennent du serveur
					if (!client_read(sckt, output, &fichiers, &socket_fichier))
						break;

                // Select_ret_val est le nombre de descripteurs où il y 
                // a eu une activité, on diminue donc sa valeur au fur
                // et à mesure.
                select_ret_val--;

            }
        }

	} while(notquit(input) && notquit(output));

	//printf("Extinction.\n");

	free(input);
	
	free_file(&fichiers);

	free_reg();

	// Fermeture de la socket
    close_socket(sckt);
    
	printf("Fin du tchat\n");
	
    return 0;
}
Esempio n. 9
0
    /** Creates socket and connects.
     *
     * creates socket and initiates tcp connection.
     */
    bool socket::connect(const std::string host, const std::string port) {

        if (!get_addr_info(host, port)) return false;
        if (!ip_endpoint_->results) return false;

        bool rc(false);

        // find a suitable interface
        for (ip_endpoint_->rp = ip_endpoint_->results;
                ip_endpoint_->rp != nullptr;
                ip_endpoint_->rp = \
                    ip_endpoint_->rp->ai_next) {

            ip_endpoint_->socket_ = ::socket(ip_endpoint_->rp->ai_family,
                    ip_endpoint_->rp->ai_socktype,
                    ip_endpoint_->rp->ai_protocol);
            if (ip_endpoint_->socket_ == -1)
                continue;

            // attempt to connect
            if (::connect(ip_endpoint_->socket_,
                    ip_endpoint_->rp->ai_addr,
                    ip_endpoint_->rp->ai_addrlen) != -1) {

                // set options
                int option = 1;
                setsockopt(ip_endpoint_->socket_,
                        SOL_SOCKET, SO_REUSEADDR,
                        (char *) &option, sizeof (option));

                rc = true;

                syslog(LOG_DEBUG, "connection to %s OK", host.c_str());

                // success
                break;
            }

            close(ip_endpoint_->socket_);
        }

        if (ip_endpoint_->rp == nullptr) {
            syslog(LOG_DEBUG, "unable to allocate interface to destination host");
            return false;
        }

        // free results
        freeaddrinfo(ip_endpoint_->results);

        // open stream for write
        if (nullptr == (ip_endpoint_->tx = \
                fdopen(ip_endpoint_->socket_, "w"))) {

            close(ip_endpoint_->socket_);
            syslog(LOG_DEBUG, "unable to open TX stream");
        } else rc = true;

        // open stream for read
        if (nullptr == (ip_endpoint_->rx = \
                fdopen(ip_endpoint_->socket_, "r"))) {

            close(ip_endpoint_->socket_);
            syslog(LOG_DEBUG, "unable to open RX stream");
        } else rc = true;

        return rc;
    }
Esempio n. 10
0
int  get_hostaddr_hostent_af(

  int             *rc,
  char            *hostname,
  unsigned short  *af_family,
  char           **host_addr,
  int             *host_addr_len)

  {
  int                    addr_rc;
  struct sockaddr_in     sa;
  char                   log_buf[LOCAL_LOG_BUF_SIZE];
  char                  *tmp_ip = NULL;

#ifdef NUMA_SUPPORT
  /* if this is a numa host, just get the parent node's address */
  char *dash;

  if ((dash = strchr(hostname,'-')) != NULL)
    {
    char *tmp;

    /* make sure to use the last dash */
    while ((tmp = strchr(dash+1,'-')))
      dash = tmp;

    if (isdigit(*(dash+1)))
      {
      /* terminate string temporarily */
      *dash = '\0';

      /* check if this resolves to a hostname without the dash */
      if ((addr_rc = get_addr_info(hostname, &sa, 3)) != 0)
        {
        /* not a numa-owned node, act normal */
        *dash = '-';
      
        addr_rc = get_addr_info(hostname, &sa, 3);
        }
      }
    /* otherwise proceed with just the parent hostname so 
     * it can be resolved */
    else
      addr_rc = get_addr_info(hostname, &sa, 3);
    }
  else
    addr_rc = get_addr_info(hostname, &sa, 3);
#else
  addr_rc = get_addr_info(hostname, &sa, 3);
#endif /* NUMA_SUPPORT */

  *rc = PBSE_NONE;

  if (addr_rc != 0)
    {
    snprintf(log_buf, sizeof(log_buf),
      "cannot resolve IP address for host '%s' herror=%d: %s",
      hostname,
      h_errno,
      hstrerror(h_errno));
      /* This is for cases where the client is running this command */
      if (log_mutex == NULL)
        fprintf(stderr, "%s\n", log_buf);
      else
        log_event(PBSEVENT_SYSTEM,PBS_EVENTCLASS_SERVER,"get_hostaddr_hostent",log_buf);

    if (h_errno == TRY_AGAIN)
      *rc = PBS_NET_RC_RETRY;
    else
      *rc = PBS_NET_RC_FATAL;

    return(*rc);
    }

  if ((tmp_ip = (char *)calloc(1, sizeof(struct in_addr) + 1)) == NULL)
    {
    *rc = PBS_NET_RC_FATAL;
    }
  else
    {
    memcpy(tmp_ip, &sa.sin_addr, sizeof(struct in_addr));
    *host_addr = tmp_ip;
    *host_addr_len = sizeof(struct in_addr);
    *af_family = sa.sin_family;
    }


  return(*rc);
  }  /* END get_hostaddr_hostent() */