
Enviado em 19/06/2021 - 22:56h
Recentemente comecei a estudar a API de sockets do Unix (Berkeley sockets) e acabei encontrando uma função bastante interessante e comumente utilizada em conexões half-duplex e full-duplex: a shutdown().int shutdown(int sockfd, int how);
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 9009
#define ADDR "127.0.0.1"
#define MAXCONN 5
int main(void) {
int sockfd;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
fprintf(stderr, "socket() -> ERROR %d: %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_pton(AF_INET, ADDR, &addr.sin_addr.s_addr);
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0 ) {
fprintf(stderr, "bind() -> ERROR %d: %s\n", errno, strerror(errno));
close(sockfd);
exit(EXIT_FAILURE);
}
if (listen(sockfd, SOMAXCONN) < 0 ) {
fprintf(stderr, "listen() -> ERROR %d: %s\n", errno, strerror(errno));
close(sockfd);
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < MAXCONN; i++) {
struct sockaddr_in client;
socklen_t size;
char caddr[INET_ADDRSTRLEN];
int new_sockfd;
memset(&client, 0, sizeof(client));
if ((new_sockfd = accept(sockfd, (struct sockaddr*)&client, &size)) < 0 ) {
fprintf(stderr, "accept() -> ERROR %d: %s\n", errno, strerror(errno));
} else {
if (inet_ntop(client.sin_family, &client.sin_addr.s_addr, caddr, sizeof(caddr)) == NULL ) {
fprintf(stderr, "inet_ntop -> ERROR %d: %s\n", errno, strerror(errno));
} else {
printf("%s\n", caddr);
}
const char msg[] = "What's up, _Bitch. Names John. You here to help me?\n";
shutdown(new_sockfd, SHUT_WR); //Usando new_sockfd o programa para, já o mesmo não acontece com o descritor sockfd
if (write(new_sockfd, msg, sizeof(msg)) < 0 ) {
fprintf(stderr, "write() -> ERROR %d: %s\n", errno, strerror(errno));
}
close(new_sockfd);
}
}
close(sockfd);
return EXIT_SUCCESS;
}
Bluefin - A nova geração de ambientes de trabalho Linux
Como atualizar sua versão estável do Debian
Cirurgia para acelerar o openSUSE em HD externo via USB
Quer auto-organizar janelas (tiling) no seu Linux? Veja como no Plasma 6 e no Gnome
Copiando caminho atual do terminal direto para o clipboard do teclado
Script de montagem de chroot automatica
Não estou conseguindo fazer funcionar meu Postfix na versão 2.4 no Deb... (0)
archlinux resolução abaixou após atualização (16)
Conselho distribuiçao brasileira (7)
Não consigo instalar distro antiga no virtualbox nem direto no hd (33)









