Skip to content

Instantly share code, notes, and snippets.

@tiagodalloca
Created December 1, 2017 10:35
Show Gist options
  • Save tiagodalloca/1628e265424368392a9d72569650fe64 to your computer and use it in GitHub Desktop.
Save tiagodalloca/1628e265424368392a9d72569650fe64 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORTA 666
#define CONEXOES 5
#define MAXDATASIZE 2000
main() {
char buffer[MAXDATASIZE];
int nsocket, newsocket;
struct sockaddr_in server_endereco;
struct sockaddr_in endereco_cliente;
int tam;
if ((nsocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
server_endereco.sin_family = AF_INET;
server_endereco.sin_port = htons(PORTA);
server_endereco.sin_addr.s_addr = INADDR_ANY; //incorpora o IP padrão do hospedeiro
bzero(&(server_endereco.sin_zero), 8);
if (bind(nsocket, (struct sockaddr *)&server_endereco,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(nsocket, CONEXOES) < 0) {
perror("listen");
exit(1);
}
while(1) {
tam = sizeof(struct sockaddr_in);
if ((newsocket = accept(nsocket, (struct sockaddr*)
&endereco_cliente,&tam)) < 0) {
perror("accept");
continue;
}
printf("Cliente conectando em %s\n", inet_ntoa(endereco_cliente.sin_addr));
if (numbytes = recv(nsocket, buffer, MAXDATASIZE, 0) == -1) {
perror("recv");
}
if (!fork()) {
buffer[numbytes] = '\0';
toupper(buffer);
if (send(newsocket, buffer, strlen(buffer), 0) == -1)
perror("send");
close(newsocket);
}
close(newsocket);
while(waitpid(-1, NULL, WNOHANG) > 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment