common.h (1863B)
1 #ifndef COMMON_H 2 #define COMMON_H 3 4 #define _GNU_SOURCE 1 5 6 #include <stddef.h> 7 #include <stdlib.h> 8 #include <stdio.h> 9 #include <unistd.h> 10 11 #include <sys/random.h> 12 13 #include <sys/types.h> 14 #include <sys/socket.h> 15 #include <netdb.h> 16 17 static int 18 get_socket(char *host, char *port, int socktype, int protocol, int passive) 19 { 20 struct addrinfo hints = { 21 .ai_family = AF_UNSPEC, 22 .ai_socktype = socktype, 23 .ai_protocol = protocol, 24 }, *addrinfo, *ptr; 25 26 int res; 27 if ((res = getaddrinfo(host, port, &hints, &addrinfo))) { 28 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(res)); 29 return -1; 30 } 31 32 int fd; 33 for (ptr = addrinfo; ptr; ptr = ptr->ai_next) { 34 fd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); 35 if (fd < 0) 36 continue; 37 38 if (passive && bind(fd, ptr->ai_addr, ptr->ai_addrlen) < 0) { 39 close(fd); 40 fd = -1; 41 continue; 42 } else if (connect(fd, ptr->ai_addr, ptr->ai_addrlen) < 0) { 43 close(fd); 44 fd = -1; 45 continue; 46 } 47 48 break; 49 } 50 51 res = fd; 52 53 if (!ptr) { 54 fprintf(stderr, "getaddrinfo: failed to connect to %s:%s\n", 55 host, port); 56 } 57 58 freeaddrinfo(addrinfo); 59 60 return res; 61 } 62 63 static int 64 get_client_socket(char *host, char *port, int socktype, int protocol) 65 { 66 return get_socket(host, port, socktype, protocol, 0); 67 } 68 69 static int 70 get_server_socket(char *host, char *port, int socktype, int protocol) 71 { 72 int fd = get_socket(host, port, socktype, protocol, 1); 73 if (fd < 0) 74 return fd; 75 76 listen(fd, 16); 77 78 return fd; 79 } 80 81 static int 82 recvall(int fd, char *buf, size_t len) 83 { 84 do { 85 ssize_t curr = recv(fd, buf, len, 0); 86 if (curr < 0) 87 return -1; 88 89 buf += curr; 90 len -= curr; 91 } while (len); 92 93 return 0; 94 } 95 96 static int 97 sendall(int fd, char *buf, size_t len) 98 { 99 do { 100 ssize_t curr = send(fd, buf, len, 0); 101 if (curr < 0) 102 return -1; 103 104 buf += curr; 105 len -= curr; 106 } while (len); 107 108 return 0; 109 } 110 111 #endif /* COMMON_H */