Skip to content

Instantly share code, notes, and snippets.

@T-X
Created May 6, 2024 19:47
Show Gist options
  • Save T-X/1b5402f810d1ebaed22ec12960773b65 to your computer and use it in GitHub Desktop.
Save T-X/1b5402f810d1ebaed22ec12960773b65 to your computer and use it in GitHub Desktop.
/*
* Compile with:
* $ gcc test.c -o /tmp/test -g -O2
*
* $ gcc --version
* gcc (Debian 13.2.0-24) 13.2.0
*
* Output:
*
* $ /tmp/test
* Before: input.sa_family: 10, output.ss_family: 0
* After: input.sa_family: 10, output.ss_family: 0
* Error: address family was not copied? 10 vs. 0
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
static int sap_get_ip4_dst(const struct sockaddr_in *input, struct sockaddr_in *output)
{
in_addr_t pdst = ntohl(input->sin_addr.s_addr);
/* this breaks it, even for AF_INET6 case? */
if (((pdst) & 0xffffff00) != 0xe0000000)
return -1;
output->sin_family = input->sin_family;
return 0;
}
static int sap_get_ip6_dst(const struct sockaddr_in6 *input, struct sockaddr_in6 *output)
{
output->sin6_family = input->sin6_family;
return 0;
}
static int copy_family(struct sockaddr *addr, struct sockaddr_storage *sap_dst)
{
switch (addr->sa_family) {
case AF_INET:
return sap_get_ip4_dst((struct sockaddr_in *)addr,
(struct sockaddr_in *)sap_dst);
case AF_INET6:
return sap_get_ip6_dst((struct sockaddr_in6 *)addr,
(struct sockaddr_in6 *)sap_dst);
}
return -1;
}
static void sap_create_socket(void)
{
struct sockaddr_storage output = { 0 };
struct sockaddr input = { 0 };
int ret;
input.sa_family = AF_INET6;
printf("Before:\tinput.sa_family: %i, output.ss_family: %i\n", input.sa_family, output.ss_family);
ret = copy_family(&input, &output);
if (ret < 0)
return;
printf("After:\tinput.sa_family: %i, output.ss_family: %i\n", input.sa_family, output.ss_family);
if (input.sa_family != output.ss_family)
fprintf(stderr, "Error: address family was not copied? %i vs. %i\n", input.sa_family, output.ss_family);
return;
}
int main(int argc, char *argv[])
{
sap_create_socket();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment