Code with Sockets locking in the middle

0
Because of college networking stuff, lately I have had experiences to learn how to deal with sockets in C. But today, trying to develop a candle game to practice, I had a rather peculiar problem. Apparently, the code I wrote does not have any syntax errors or anything, but when trying to run after compiling with GCC (5.4), it happens that the program hangs in the second printf with "All right!" After option "2" be stored and inserted into the variable "type", well in the else if. If anyone wants or can, I would even be grateful to receive some feedback on the code:

    else if(tipo == 2){
    h = gethostbyname("127.0.0.1");
    if(h == NULL){
        printf("Impossível localizar o host");
        exit(1);
    }
    // Setup do servidor. Primeiro faz a cópia bit-a-bit do endereço do server para a struct, depois se seta o sin_family na struct e então a porta
    memcpy((char *) &jog1.sin_addr.s_addr, h->h_addr_list, h->h_length);
    jog1.sin_family = AF_INET;
    jog1.sin_port = htons(PORTA);

    jog2.sin_addr.s_addr = htonl(INADDR_ANY);
    jog2.sin_port = (0);
    jog2.sin_family = AF_INET;

    soquete = socket(AF_INET, SOCK_DGRAM, 0);
    if(soquete < 0){
        printf("\nOps! Erro ao criar o soquete... Tente novamente\n");
        exit(1);
    }
    binded = bind(soquete, (struct sockaddr *) &jog2, sizeof(jog2));
    if(binded < 0){
        printf("\nErro ao bindar a porta! Tente novamente\n");
        close(soquete);
        exit(1);
    }
    printf("\nTudo certo! Enviando dados ao jogador 1");
    printf("...");
    printf("\nTudo certo! Enviando dados ao jogador 1");
    printf("\nTudo certo! Enviando dados ao jogador 1");
    clilen = sizeof(jog2);
    msg[0] = (char) PRONTO;
    envio = sendto(soquete, msg, sizeof((char) PRONTO) + 1, 0, (struct sockaddr *) &jog1, sizeof(jog1));
    resposta = recvfrom(soquete, msg, MAX_MSG, 0, (struct sockaddr *) &jog1, &clilen);
    if(msg[0] == (char) PRONTO){
        printf("\nJogador 1 conectado com sucesso! %u:%u", ntohl(jog1.sin_addr.s_addr), ntohs(jog1.sin_port));
    }
    else{
        printf("\nErro! Comando inválido recebido!");
        close(soquete);
        exit(1);
    }
}
    
asked by anonymous 07.10.2017 / 03:10

0 answers