c AF_INET
This commit is contained in:
parent
0575eaa4cc
commit
630e49571a
38
~/C/AF_INET_sockets/echo_client.c
Normal file
38
~/C/AF_INET_sockets/echo_client.c
Normal 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;
|
||||||
|
}
|
48
~/C/AF_INET_sockets/echo_server.c
Normal file
48
~/C/AF_INET_sockets/echo_server.c
Normal 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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user