Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #define PORTA 8082
- /*
- * Servidor para aceitar comunicação com Cliente
- * Parametros necessários: NENHUM
- */
- void error(const char *msg);
- int main(int argc, char *argv[]) {
- // Variaveis do Servidor
- int sockfd, newsockfd, portno, n;
- socklen_t clilen;
- char buffer[256];
- struct sockaddr_in serv_addr, cli_addr;
- // Obtendo porta padrão ou por argumento
- if (argc < 2)
- portno = PORTA;
- else
- portno = atoi(argv[1]);
- // Ativando o socket
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (sockfd < 0)
- error("Erro, não foi possivel ativar o socket");
- bzero((char *) &serv_addr, sizeof(serv_addr));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = INADDR_ANY;
- serv_addr.sin_port = htons(portno);
- if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
- error("Erro, não foi possivel fazer a bindagem, escolha outra porta");
- }
- listen(sockfd,5);
- printf("---------------------------------\n");
- printf("Servidor iniciado com sucesso!\n");
- printf("Porta: %d \n", portno);
- printf("---------------------------------\n");
- // Aceitando conexões
- clilen = sizeof(cli_addr);
- newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
- // Conexão estabilizada, recebendo mensagens
- while(newsockfd>0){
- bzero(buffer,256);
- n = read(newsockfd,buffer,255);
- // Imprime mensagem
- printf(" MSG: %s\n",buffer);
- // Verificando resposta
- n = write(newsockfd,"(OK)\n",8);
- if (n < 0)
- error("(ERRO->Resposta não recebida)");
- else
- printf("(OK->Resposta recebida)");
- }
- if (newsockfd < 0)
- error("Erro ao aceitar o Socket ");
- // Fechando conexões e encerrando o programa
- close(newsockfd);
- close(sockfd);
- return 0;
- }
- void error(const char *msg) {
- printf("%s", msg);
- exit(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement