1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #include <sys/socket.h>
-
- #define PORT 5000
- #define BUFFER_SIZE 1024
-
- int main(int argc, char *argv[]) {
- char *endpoint = "";
- char *data = ""; // Data to be sent in the POST request
- if (argc > 1) {
- endpoint = argv[1];
- }
- if (argc > 2) {
- data = argv[2];
- }
-
- char request[BUFFER_SIZE];
- snprintf(request, BUFFER_SIZE, "POST /%s HTTP/1.1\r\nHost: localhost:5000\r\nContent-Type: application/json\r\nContent-Length: %ld\r\n\r\n%s", endpoint, strlen(data), data);
-
- int sockfd;
- struct sockaddr_in server_addr;
- char buffer[BUFFER_SIZE];
-
- // Create socket
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (sockfd < 0) {
- perror("Error in socket creation");
- exit(EXIT_FAILURE);
- }
-
- // Set up server address
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- server_addr.sin_port = htons(PORT);
-
- // Connect to server
- if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
- perror("Error in connection");
- exit(EXIT_FAILURE);
- }
-
- // Send HTTP request
- if (send(sockfd, request, strlen(request), 0) != strlen(request)) {
- perror("Error in sending request");
- exit(EXIT_FAILURE);
- }
-
- // Receive data from server
- ssize_t total_bytes_received = 0;
- ssize_t bytes_received;
- while ((bytes_received = recv(sockfd, buffer, BUFFER_SIZE, 0)) > 0) {
- // Display received data
- fwrite(buffer, 1, bytes_received, stdout);
- total_bytes_received += bytes_received;
- }
-
- if (bytes_received < 0) {
- perror("Error in receiving data");
- exit(EXIT_FAILURE);
- }
-
- // Close socket
- close(sockfd);
-
- return 0;
- }
|