c AF_INET

This commit is contained in:
Alexander Popov 2023-06-18 22:05:44 +03:00
parent 0575eaa4cc
commit 630e49571a
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
2 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,38 @@
/* 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)];
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;
}

View File

@ -0,0 +1,48 @@
/* 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;
}