diff options
author | Oxore <oxore@protonmail.com> | 2023-12-12 23:36:12 +0300 |
---|---|---|
committer | Oxore <oxore@protonmail.com> | 2023-12-12 23:36:12 +0300 |
commit | 17c01af9dea19ab9e553ef0db775e43f74a752e5 (patch) | |
tree | 39647860089b25a026841a94d0c1b5323139f134 /server.c | |
parent | 0b86520b9ff166cd285d077d3d8192653e7d95e9 (diff) |
Impl printing source address
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 21 |
1 files changed, 17 insertions, 4 deletions
@@ -15,7 +15,7 @@ int main(void) } struct sockaddr_in const serveraddr = { .sin_family = AF_INET, - .sin_port = htons(50037), + .sin_port = htons(50037u), .sin_addr.s_addr = htonl(INADDR_ANY), }; if (bind(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { @@ -23,14 +23,27 @@ int main(void) return 1; } for (;;) { + struct sockaddr_in source_address; char buffer[200]; - int const length = recvfrom(fd, buffer, sizeof(buffer) - 1, 0, NULL, 0); + 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; } - buffer[length] = '\0'; - printf("%d bytes: '%s'\n", length, buffer); + 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); } |