Code: Select all
#include
#include
#include
#include
#include
#include
#define MYPORT "3490"
#define BACKLOG 10
#define BUFFERSIZE 4096
int main() {
struct sockaddr_storage incoming_addr;
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int err = getaddrinfo(NULL, MYPORT, &hints, &res);
if (err != 0) {
printf("error: %s", gai_strerror(err));
exit(2);
}
int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd == -1) {
perror("can't create socket");
exit(2);
}
if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) {
perror("can't bind socket");
exit(2);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("can't connect to host");
exit(2);
}
socklen_t addr_size;
addr_size = sizeof incoming_addr;
int fd = accept(sockfd, (struct sockaddr *)&incoming_addr, &addr_size);
if (fd == -1)
perror("accept denied error");
// 👇 Allocate new buffer
char *buf = malloc(BUFFERSIZE);
int recv_len;
do {
recv_len = recv(fd, buf, BUFFERSIZE, 0);
if (recv_len == -1) {
perror("connection interrupted");
exit(2);
}
buf[recv_len] = '\0';
printf("%s %d; %s\n", "Bytes received:", recv_len, "Message:");
printf("%s\n", buf);
send(fd, "pong", 4, 0);
} while ((recv_len != -1));
close(fd);
close(sockfd);
}
Code: Select all
Bytes received: 4; Message:
Hell
Jetzt habe ich keine Ahnung, warum ich 4 Bit bekomme, nur eine Annahme Das kann ich nicht bestätigen.
Ich werde mich weiter umschauen, aber wenn Sie mir Feedback geben, wäre es hilfreich.