💾 Archived View for gmi.noulin.net › gitRepositories › spartserv › file › spartclient.c.gmi captured on 2023-07-10 at 15:39:10. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-01-29)
-=-=-=-=-=-=-
spartclient.c (2001B)
1 // Usage: spartclient hostname port path 2 #include <stdio.h> 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <netdb.h> 6 #include <netinet/in.h> 7 #include <string.h> 8 #include <stdlib.h> 9 #include <ctype.h> 10 #include <unistd.h> 11 12 int64_t parseInt(const char *string) { 13 while (!isdigit(*string) && *string != '-' && *string != 0) { 14 string++; 15 } 16 int64_t r = strtoll(string, NULL, 10); 17 return(r); 18 } 19 20 int main(int ac, char **av){ 21 int sock; 22 struct sockaddr_in server; 23 struct hostent *hp; 24 int mysock; 25 char buf[8192] = {0}; 26 int rval; 27 int i; 28 29 if (ac < 4) { 30 puts("Usage: spartclient hostname port path"); 31 return 0; 32 } 33 34 sock = socket(AF_INET, SOCK_STREAM, 0); 35 if (sock < 0){ 36 perror("Failed to create socket"); 37 } 38 39 server.sin_family = AF_INET; 40 41 hp = gethostbyname(av[1]); 42 if (hp==0) { 43 perror("gethostbyname failed"); 44 close(sock); 45 exit(1); 46 } 47 48 memcpy(&server.sin_addr, hp->h_addr, hp->h_length); 49 50 int64_t port = parseInt(av[2]); 51 52 if (port < 1 || port > 65000) { 53 printf("Invalid port %d.\n", port); 54 return 1; 55 } 56 57 server.sin_port = htons(port); 58 59 if (connect(sock,(struct sockaddr *) &server, sizeof(server))){ 60 perror("connect failed"); 61 close(sock); 62 exit(1); 63 } 64 65 // build request 66 size_t len = strlen(av[1]); 67 memcpy(buf, av[1], len); 68 buf[len] = ' '; 69 char *cursor = buf + len + 1; 70 len = strlen(av[3]); 71 memcpy(cursor, av[3], len); 72 memcpy(cursor + len, " 0\r\n", strlen(" 0\r\n")); 73 cursor += len + strlen(" 0\r\n"); 74 75 // send request 76 if(send(sock, buf, cursor - buf, 0) < 0){ 77 perror("send failed"); 78 close(sock); 79 exit(1); 80 } 81 82 // reveice server response 83 rval = recv(sock, buf, sizeof(buf)-1 /* -1 to add end of string before printing */, 0); 84 if (rval != -1 && rval != 0) { 85 buf[rval] = 0; 86 puts(buf); 87 } 88 89 close(sock); 90 } 91