Servidor de arquivos (Cliente/servidor)
Publicado por Vanderson Lucio Rodrigues 12/12/2005
[ Hits: 11.233 ]
Homepage: http://www.vandersongold.com.br
Este programa implementa Servidor de arquivos que faz um Upload de
arquivos usando algumas chamadas de sockets.
Ps.: Você pode encontrar um Cliente para este servidor em " " "http://www.vivaolinux.com.br/contribuir/scripts/verScript.php?codigo=1521 ", feito em Python.
/* @file * --> Servidor <-- * * * Este programa implementa Servidor de arquivos que faz um Upload de * arquivos usando algumas chamadas de sockets. * * * $Revision: 1.10 $ $Date: 2005/11/21 19:24:22 $ * * (C) Copyright 2005 Vanderson Rodrigues * */ #include <getopt.h> #include <time.h> #include <sys/utsname.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #define BUF_SIZE 4096 #define QUEUE_SIZE 10 #define FILE_MODE 0664 void sistema(void) { struct utsname u; uname(&u); printf("Sistema Operacional : %s - Release %s\n", u.sysname, u.release); printf("Servidor: Rodando em %s\n", u.nodename); } void limpar(void) { printf("{FONTE}33[2J"); /* limpa a tela */ printf("{FONTE}33[1H"); /* poe o curso no topo */ } void fatal(char *string) { printf("%s", string); exit(EXIT_FAILURE); } void uso (char *prognome) { printf("Uso: %s [-p porta] [-h]\n", prognome); printf("\t porta - Porta TCP\n"); printf("\t h - Mostra Essa ajuda\n"); exit(EXIT_SUCCESS); } int main(int argc, char **argv) { int s, b, l, fd, sa, bytes, on = 1; char buf[BUF_SIZE]; /* buffer para saida do arquivo */ struct sockaddr_in local; /* Pega Endereco IP */ struct sockaddr_in remoto; /* Pega Endereco IP */ int sin_size, optch, porta; char *client_ip, stropts[] = "hp:"; char arq_nome[256], arq_tamanho[256]; time_t time1, time2; while ((optch = getopt(argc, argv, stropts)) != EOF) { switch (optch) { case 'h': uso(argv[0]); return 0; case 'p': porta = atoi(optarg); break; default: fprintf(stderr, "digite -h para ajuda\n"); exit(EXIT_FAILURE); } } if ( argc != 3) { fprintf(stderr,"Erro: Faltando Argumentos.\n"); fputs("Use -h para ajuda.\n",stderr); exit(EXIT_FAILURE); } /* Constroi a estrutura de endereco pra amarrar com Servidor. */ memset(&local, 0, sizeof(local)); /* zera local */ local.sin_family = AF_INET; local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(porta); /* Cria socket */ if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ) fatal("Falha ao Cria Socket\n"); /* diz pra aceitar mais de uma conexao */ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)); if ((b = bind(s, (struct sockaddr *) &local, sizeof(local))) < 0) fatal("Bind Falhou\n"); /* Especifica o tamanho da fila */ if ((l = listen(s, QUEUE_SIZE)) < 0) fatal("listen failed"); limpar(); sistema(); /* Loop principal. Esperando por conexao */ while (1) { printf("Servidor: Aguardando Conexao.\n"); sin_size = sizeof(struct sockaddr_in); /* bloco para aceitar a requisicaoi */ if ((sa = accept(s,( struct sockaddr *)&remoto, &sin_size)) < 0) fatal("Falha no accept\n"); time(&time1); client_ip = inet_ntoa(remoto.sin_addr); printf(">>> Servidor: Conectado a %s Porta: %d\n", client_ip, remoto.sin_port); /* Recebe e imprime na tela o nome do Arquivo */ if ((bytes = recv(sa, buf, 256, 0)) < 0) fprintf(stderr, "Falha no recebimento de dados\n"); buf[bytes] = '{FONTE}'; strcpy(arq_nome, buf); printf(">>> Recebendo Arquivo: "); printf("\"%s\" --> ", buf); /* zera buf */ bzero(buf, BUF_SIZE); /* Recebe e imprime o tamanho do Arquivo */ if ((bytes = recv(sa, buf, 256, 0)) < 0) fprintf(stderr, "Falha no recebimento de dados\n"); buf[bytes] = '{FONTE}'; strcpy(arq_tamanho, buf); printf("%sK \n", buf); printf(">>> Aguarde...\n"); /* Cria diretorio com IP do cliente para amarmazenar o arquivo * recebido do cliente */ mkdir(client_ip, 0766); chdir(client_ip); /* cria o arquivo */ if((fd = open(arq_nome, O_RDWR | O_CREAT, FILE_MODE)) < 0) { fatal("Nao foi possivel abrir arquivo\n"); close(fd); close(sa); continue; } /* Recebe os dados do arquivo */ while ((bytes = recv(sa, buf, BUF_SIZE, 0)) > 0) { write(fd, buf, bytes); } time(&time2); /* Informa Na saida Padrao o onde o arquivo foi armazenado */ printf(">>> Arquivo Recebido com Sucesso !\n"); printf(">>> Aviso:\n"); printf(">>>\tCheque o Arquivo \"%s\" no Diretorio .\"/%s\"\n>>>\n", arq_nome, client_ip); chdir(".."); /* Volta ao diretorio de origem */ close(fd); /* Fechar o arquivo */ close(sa); /* Encerra a conexao */ printf(">>> Dados Transferidos em : %d segundos\n", time2 - time1); printf(">>> Conexao Encerrada com %s\n\n", client_ip); } return 0; }
Interface gráfica para o Skype Web
HtmlPageDown - Baixe páginas HTML (cURL)
Deixando o Gnome bonitão em qualquer distribuição
Como ativar o módulo de cancelamento de ruído no Pipewire
Como escolher o melhor escalonador de CPU para melhorar o desempenho da máquina
Curiosidade sobre DOOM Guy e Isabelle de Animal Crossing
Inicializando servidor Ubuntu na AWS e rodando apache em Container
Baixar e ler mangás grátis no Linux e no Android
Instalando Brave Browser no Fedora 40
Problema com o Apache NetBeans IDE 21 no Debian 12 (1)
GRUB do Debian 12 não detecta segundo Linux instalado em partição BTRF... (26)
Sistema trava no boot após atualização do driver nVidia (GeForce 1070)... (4)