diff options
author | Oskar <[email protected]> | 2024-06-03 10:46:16 +0200 |
---|---|---|
committer | Oskar <[email protected]> | 2024-06-03 10:46:16 +0200 |
commit | cf86eea3ef47ce4444b99edff866a7d9836bd763 (patch) | |
tree | b4807c241595755035557b44001bc053e513917c /client-DGRAM.c | |
parent | 4333fba71bbdadfe078aa7ebbe9194c6fc35af22 (diff) |
udp client-DGRAM
Diffstat (limited to 'client-DGRAM.c')
-rw-r--r-- | client-DGRAM.c | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/client-DGRAM.c b/client-DGRAM.c new file mode 100644 index 0000000..f447d37 --- /dev/null +++ b/client-DGRAM.c @@ -0,0 +1,91 @@ +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> +#include <stdio.h> +#include <string.h> +#include <stdint.h> +#include <unistd.h> +#include <stdbool.h> +#include <fcntl.h> +#include <stdlib.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#include <signal.h> + +#define __FAIL EXIT_FAILURE +#define BACKLOG 2 +#define __PORT "62000" +#define BUF_SZ_2 2048 + +int sockfd = -1; +size_t bytes_sent = 0; +struct addrinfo *resfreer; +struct addrinfo *pglobal; + +void talk_to_server (int sockfd) { + + while (1) { + char editbuffer[BUF_SZ_2]; + fprintf(stdout, ": "); + + char *fgs = fgets(editbuffer, BUF_SZ_2, stdin); + socklen_t fgs_len = strlen(editbuffer); + if (fgs == NULL) { + continue; + } + + bytes_sent = bytes_sent + sendto(sockfd, editbuffer, fgs_len, 0, pglobal->ai_addr, pglobal->ai_addrlen); + } +} + +void INThandler() { + + fprintf(stderr, "\nbytes sent: %ld\n", bytes_sent); + freeaddrinfo(resfreer); + close(sockfd); + exit(0); +} + +int main (int argc, char *argv[]) { + + if (argc != 2) { + fprintf(stderr, "USAGE: %s [IP]\n", argv[0]); + exit(__FAIL); + } + + int gai_result; + struct addrinfo hints; + struct addrinfo *res; + struct addrinfo *p; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + + gai_result = getaddrinfo(argv[1], __PORT, &hints, &res); + if (gai_result != 0) { + fprintf(stderr, "getaddrinfo: %d\n", gai_result); + exit(__FAIL); + } + + for (p = res ; p != NULL ; p = p->ai_next) { + + sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); + if (sockfd == -1) { + fprintf(stderr, "socket fail\n"); + continue; + } else { + pglobal = p; + } + + } + if (sockfd == -1) { + close(sockfd); + exit(__FAIL); + } + + signal(SIGINT, INThandler); + resfreer = res; + talk_to_server(sockfd); + + return 0; +} |