-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsatellite.c
More file actions
72 lines (61 loc) · 1.82 KB
/
satellite.c
File metadata and controls
72 lines (61 loc) · 1.82 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
// server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUFSIZE 4096
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
return 1;
}
int port = atoi(argv[1]);
if (port <= 0) {
fprintf(stderr, "Invalid port: %s\n", argv[1]);
return 1;
}
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket");
return 1;
}
struct sockaddr_in srv;
memset(&srv, 0, sizeof(srv));
srv.sin_family = AF_INET;
srv.sin_addr.s_addr = htonl(INADDR_ANY);
srv.sin_port = htons(port);
if (bind(sock, (struct sockaddr*)&srv, sizeof(srv)) < 0) {
perror("bind");
close(sock);
return 1;
}
printf("UDP server listening on port %d\n", port);
for (;;) {
char buf[BUFSIZE];
struct sockaddr_in cli;
socklen_t cli_len = sizeof(cli);
ssize_t n = recvfrom(sock, buf, sizeof(buf) - 1, 0,
(struct sockaddr*)&cli, &cli_len);
if (n < 0) {
perror("recvfrom");
continue;
}
buf[n] = '\0';
char client_addr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &cli.sin_addr, client_addr, sizeof(client_addr));
printf("Received %zd bytes from %s:%d: %s\n",
n, client_addr, ntohs(cli.sin_port), buf);
// Example behavior: echo message back to sender
ssize_t sent = sendto(sock, buf, n, 0, (struct sockaddr*)&cli, cli_len);
if (sent < 0) {
perror("sendto");
} else {
printf("Echoed %zd bytes back to %s:%d\n", sent, client_addr, ntohs(cli.sin_port));
}
}
close(sock);
return 0;
}