heis/UDP/main.c

68 lines
1.1 KiB
C
Executable File

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "udp.h"
#define LINE_SIZE 256
static void receive_function(udp_packet_t packet)
{
putchar(packet);
fflush(stdout);
}
int main(int argc, char *argv[])
{
int port;
char line[LINE_SIZE];
char server[100];
if (argc < 2) {
printf("udp: not enough input arguments\n");
return 1;
}
else if (!strchr(argv[1], ':')) {
printf(
"Usage:\n"
" udp target:port\n"
"or:\n"
" udp broadcast:port\n"
);
return 1;
}
port = atoi(strchr(argv[1], ':')+1);
*strchr(argv[1], ':') = '\0';
if (!strcmp(argv[1], "broadcast")) {
if (udp_get_broadcast_address("eth1", server, sizeof(server)) < 0) {
printf("Error: Cannot determine broadcast address\n");
exit(1);
}
}
else {
strncpy(server, argv[1], sizeof(server));
}
printf("Using %s:%d\n", server, port);
udp_listen(port, &receive_function);
while (1) {
int i;
fgets(line, LINE_SIZE, stdin);
for (i = 0; line[i] != '\0'; i++) {
udp_packet_t packet = line[i];
udp_send_packet(server, port, packet);
}
}
}