Files
42-exam06/explore/03_accept_recv.c

89 lines
2.4 KiB
C

/* Experiment 03 — accept() and the truth about TCP chunking + EOF.
*
* Build: cc -Wall -Wextra -Werror 03_accept_recv.c -o 03_accept_recv
* Run: ./03_accept_recv 8081
*
* In another terminal:
* nc 127.0.0.1 8081 -> type "hello" + Enter, then more text, watch this
* program print one line per recv() with its size
* Ctrl-D / Ctrl-C -> watch the final recv() return 0 (EOF)
*
* Scripted split-line test (same connection, "par" then later "tial\n"):
* send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
* { printf 'par'; sleep 1; printf 'tial\n'; } | send 8081
*
* Lesson: recv() returns whatever bytes are available, not "one message".
* A logical line can arrive in pieces; the final 0 is EOF.
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main(int argc, char **argv)
{
struct sockaddr_in addr; // for the host configration
unsigned char buf[64]; // message size
ssize_t n;
ssize_t i;
int sfd; // socket fd
int cfd; //
if (argc != 2)
{
fprintf(stderr, "usage: %s PORT\n", argv[0]);
return (1);
}
sfd = socket(AF_INET, SOCK_STREAM, 0); // init the socket fd
if (sfd < 0)
{
perror("socket");
return (1);
}
memset(&addr, 0, sizeof(addr)); // remove the struct data
addr.sin_family = AF_INET; // add the configrations
addr.sin_addr.s_addr = htonl(2130706433); // add the configrations
addr.sin_port = htons(atoi(argv[1])); // add the configrations
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) // use the socket alocate the port
{
perror("bind");
return (1);
}
if (listen(sfd, 10) < 0) // listn to the network
{
perror("listen");
return (1);
}
printf("waiting: nc 127.0.0.1 %s\n", argv[1]);
cfd = accept(sfd, NULL, NULL); // connection fd when accetp the connection
if (cfd < 0)
{
perror("accept");
return (1);
}
printf("accepted! listening fd = %d, conversation fd = %d (a NEW one)\n",
sfd, cfd);
while ((n = recv(cfd, buf, sizeof(buf), 0)) > 0) //byte get revived form the connection
{
printf("recv -> %zd bytes: [", n);
i = 0;
while (i < n)
{
if (isprint(buf[i]))
printf("%c", buf[i]);
else
printf(".");
i++;
}
printf("]\n");
fflush(stdout);
}
printf("recv returned %zd <- EOF (peer closed) or error. Bye.\n", n);
close(cfd);
close(sfd);
return (0);
}