How to cast sockaddr_storage and avoid breaking strict-aliasing rules

后端 未结 4 947
情书的邮戳
情书的邮戳 2020-12-12 22:57

I\'m using Beej\'s Guide to Networking and came across an aliasing issue. He proposes a function to return either the IPv4 or IPv6 address of a particular struct:



        
4条回答
  •  醉梦人生
    2020-12-12 23:08

    I recently had a similar alias warning on HPUX system when trying to write code to get the MAC address of the machine

    The &(((struct sockaddr_in *)addr)->sin_addr) complains about strict-aliasing rules

    This is the code in some context

     char ip[INET6_ADDRSTRLEN] = {0};
     strucut sockaddr *addr
    
     ...
     get addr from ioctl(socket,SOCGIFCONF...) call
     ...
     inet_ntop(AF_INET, &(((struct sockaddr_in *)addr)->sin_addr),ip,sizeof ip);
    

    I overcame the aliasing warning by doing the following

    struct sockaddr_in sin;
    memcpy(&sin,addr,sizeof(struct sockaddr));
    inet_ntop(AF_INET, &sin.sin_addr,ip,sizeof ip);
    

    And whilst this is potentially dangerous I added the following lines before it

     static_assert(sizeof(sockaddr)==sizeof(sockaddr_in));
    

    I'm not sure if that is something would be considered bad practice, but it worked and was cross platform to other *Nix flavors and compilers

提交回复
热议问题