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

38 lines
767 B
C
Raw Normal View History

2023-06-18 22:05:44 +03:00
/* https://rsdn.org/article/unix/sockets.xml */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
char message[] = "Hello there!\n";
char buf[sizeof(message)];
2024-04-27 23:54:46 +03:00
int main() {
int sock;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(3425); // или любой другой порт...
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("connect");
exit(2);
}
send(sock, message, sizeof(message), 0);
recv(sock, buf, sizeof(message), 0);
printf(buf);
close(sock);
return 0;
2023-06-18 22:05:44 +03:00
}