Repository navigation
Expand file tree
/
Copy pathuser2.c
More file actions
90 lines (76 loc) · 2.41 KB
/
Copy pathuser2.c
File metadata and controls
90 lines (76 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "ksocket.h"
#include <errno.h>
#define MY_IP "127.0.0.1"
#define DEST_IP "127.0.0.1"
#define MY_PORT 8081
#define DEST_PORT 8080
int main(void)
{
printf("[User2] Receiver starting...\n");
/* create KTP socket and bind — receiver also needs to bind */
int sockfd = k_socket(AF_INET, SOCK_KTP, 0);
if (sockfd < 0)
{
perror("k_socket failed");
exit(1);
}
printf("[User2] KTP socket created (id=%d)\n", sockfd);
struct sockaddr_in my_addr, dest_addr;
memset(&my_addr, 0, sizeof(my_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MY_PORT);
my_addr.sin_addr.s_addr = inet_addr(MY_IP);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(DEST_PORT);
dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);
if (k_bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr),
(struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0)
{
perror("k_bind failed");
exit(1);
}
printf("[User2] Bound %s:%d ← %s:%d\n", MY_IP, MY_PORT, DEST_IP, DEST_PORT);
FILE *fp = fopen("received_output.txt", "w");
if (!fp)
{
perror("fopen output");
exit(1);
}
char buf[MSG_SIZE];
size_t total_received = 0;
int chunk_count = 0;
printf("[User2] Waiting for data...\n");
/* keep reading until we get the end marker from user1 */
while (1)
{
memset(buf, 0, MSG_SIZE);
ssize_t bytes = k_recvfrom(sockfd, buf, MSG_SIZE, 0, NULL, NULL);
if (bytes > 0)
{
if (strncmp(buf, "__END__", 7) == 0)
{
printf("[User2] Received END marker. Transfer complete.\n");
break;
}
fwrite(buf, 1, strnlen(buf, MSG_SIZE), fp);
total_received += bytes;
chunk_count++;
printf("[User2] Received chunk %d (%zu bytes total)\n", chunk_count, total_received);
}
else if (errno == ENOMESSAGE)
{
usleep(10000); /* nothing ready yet, poll again shortly */
}
else
{
perror("[User2] k_recvfrom failed");
break;
}
}
fclose(fp);
printf("[User2] Saved %d chunks (%zu bytes) → received_output.txt\n", chunk_count, total_received);
k_close(sockfd);
printf("[User2] Socket closed. Exiting.\n");
return 0;
}