snipplets.dev/snipplets/code/C/AF_INET_sockets/echo_server.c
2023-08-05 22:45:06 +03:00

49 lines
979 B
C

/* https://rsdn.org/article/unix/sockets.xml */
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
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);
}
while(1) {
bytes_read = recv(sock, buf, 1024, 0);
if (bytes_read <= 0) break;
send(sock, buf, bytes_read, 0);
}
close(sock);
}
return 0;
}