1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #define PORT 8080
- int main() {
- int sockfd;
- char buffer[50];
- char sbuf[50];
- struct sockaddr_in server_addr, client_addr;
- socklen_t client_len;
- if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
- perror("Socket creation failed");
- exit(EXIT_FAILURE);
- }
- memset(&server_addr, 0, sizeof(server_addr));
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = INADDR_ANY; // Bind to any address
- server_addr.sin_port = htons(PORT);
- if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
- perror("Bind failed");
- close(sockfd);
- exit(EXIT_FAILURE);
- }
- printf("Server listening on port %d\n", PORT);
- while (1) {
- client_len = sizeof(client_addr);
- int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_len);
- buffer[n] = '\0'; // Null-terminate the received string
- printf("Received message: %s\n", buffer);
- int length = n;
-
- sprintf(sbuf,"%d",n);
- sendto(sockfd, sbuf, sizeof(sbuf), 0, (const struct sockaddr *)&client_addr, client_len);
- }
- close(sockfd);
- return 0;
- }
|