123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #define PORT 8080
- #define BUFFER_SIZE 1024
- void main()
- {
- int sock_value;
- char buffer[BUFFER_SIZE];
- struct sockaddr_in server_addr={0};
- socklen_t server_len = sizeof(server_addr);
- //Create UDP socket
- if ((sock_value = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
- {
- perror("Socket creation failed");
- exit(EXIT_FAILURE);
- }
- server_addr.sin_family = AF_INET;
- server_addr.sin_port = htons(PORT);
- // Convert IP address from text to binary form
- if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
- {
- perror("Invalid address / Address not supported");
- close(sock_value);
- exit(EXIT_FAILURE);
- }
- printf("Enter a message to send to the server: ");
- fgets(buffer, sizeof(buffer), stdin);
- // Remove trailing newline character from fgets
- buffer[strcspn(buffer, "\n")] = '\0';
- //
- // Send message to the server
- sendto(sock_value, (const char *)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&server_addr, server_len);
- printf("Message sent to server: %s\n", buffer);
- //receive
- int n = recvfrom(sock_value, (char *)buffer, BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&server_addr, &server_len);
- buffer[n] = '\0'; // Null-terminate the received data
- printf("Server responded with message length: %s\n", buffer);
- //
- //Close the socket
- close(sock_value);
- }
|