cast from sockaddr * to sockaddr_in * increases required alignment

后端 未结 3 1743
情书的邮戳
情书的邮戳 2021-01-05 13:53

The compiler produces this warning when I\'m working with some code which looks like -

....

for(p = res; p != NULL; p = p->ai_next) {
    void *addr;
           


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 14:40

    To elaborate on the memcpy version. I thnk this is needed for ARM which cannot have misalligned data.

    I created a struct that contains just the first two fields (I only needed port)

    struct sockaddr_in_header {
        sa_family_t    sin_family; /* address family: AF_INET */
        in_port_t      sin_port;   /* port in network byte order */
    };
    

    Then to get the port out, I used memcpy to move the data to the stack

    struct sockaddr_in_header   sinh;
    unsigned short              sin_port;
    
    memcpy(&sinh, conn->local_sockaddr, sizeof(struct sockaddr_in_header));
    

    And return the port

    sin_port = ntohs(sinh.sin_port);
    

    This answer is really related to getting the port on Arm

    How do I cast sockaddr pointer to sockaddr_in on Arm

    The powers that be think that to be the same question as this one, however I dont want to ignore warnings. Experience has taught me that is a bad idea.

提交回复
热议问题