Skip to content

Commit f73c58f

Browse files
committed
Add UDP sender utility for sending messages to a specified IP address
1 parent 8069ae5 commit f73c58f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

bin/udp_sender.c

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <sys/types.h>
3+
#include <sys/socket.h>
4+
#include <netinet/in.h>
5+
#include <arpa/inet.h>
6+
#include <unistd.h>
7+
8+
int main(int argc, char *argv[]) {
9+
int sock;
10+
struct sockaddr_in addr;
11+
ssize_t n;
12+
13+
if (argc != 3) {
14+
printf("Usage: udp_sender <dest_ip> <message>");
15+
return 1;
16+
}
17+
18+
char* dest_ip = argv[1];
19+
char* message = argv[2];
20+
21+
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
22+
if (sock == -1) {
23+
perror("socket");
24+
return 1;
25+
}
26+
27+
addr.sin_family = AF_INET;
28+
addr.sin_port = htons(12345);
29+
addr.sin_addr.s_addr = inet_addr(dest_ip);
30+
31+
n = sendto(sock, message, 5, 0, (struct sockaddr *)&addr, sizeof(addr));
32+
if (n < 1) {
33+
perror("sendto");
34+
return 1;
35+
}
36+
37+
close(sock);
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)