// Initially based on https://stackoverflow.com/a/35570418 #include #include #include #include #include int main(void) { int const fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket failed"); return 1; } struct sockaddr_in const serveraddr = { .sin_family = AF_INET, .sin_port = htons(50037u), .sin_addr.s_addr = htonl(INADDR_ANY), }; if (bind(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { perror("bind failed"); return 1; } for (;;) { struct sockaddr_in source_address; char buffer[200]; socklen_t source_address_len = sizeof(source_address); int const length = recvfrom( fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&source_address, &source_address_len); if (length < 0) { perror("recvfrom failed"); break; } uint32_t const addr = ntohl(source_address.sin_addr.s_addr); uint8_t const a0 = addr >> 24; uint8_t const a1 = addr >> 16; uint8_t const a2 = addr >> 8; uint8_t const a3 = addr; printf("%d bytes: '%.*s' from %u.%u.%u.%u:%u\n", length, (int)length, buffer, a0, a1, a2, a3, source_address.sin_port); } close(fd); }