snipplets.dev/code/C/AF_INET_sockets/echo_server.c

49 lines
887 B
C
Raw Normal View History

2023-06-18 22:05:44 +03:00
/* https://rsdn.org/article/unix/sockets.xml */
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
2024-04-27 23:54:46 +03:00
int main() {
int sock, listener;
struct sockaddr_in addr;
char buf[1024];
int bytes_read;
listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener < 0) {
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(3425);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
exit(2);
}
listen(listener, 1);
while (1) {
sock = accept(listener, NULL, NULL);
if (sock < 0) {
perror("accept");
exit(3);
2023-06-18 22:05:44 +03:00
}
2024-04-27 23:54:46 +03:00
while (1) {
bytes_read = recv(sock, buf, 1024, 0);
if (bytes_read <= 0)
break;
send(sock, buf, bytes_read, 0);
2023-06-18 22:05:44 +03:00
}
2024-04-27 23:54:46 +03:00
close(sock);
}
2023-06-18 22:05:44 +03:00
2024-04-27 23:54:46 +03:00
return 0;
2023-06-18 22:05:44 +03:00
}