casting sockaddr_storage as sockaddr_in for inet_ntop

前端 未结 2 1105
孤街浪徒
孤街浪徒 2020-12-18 12:14

I am trying to cast a sockaddr_storage to a sockadd_in, so that i can print out the source ip address of a datagram packet, i do not seem to be able to get the cast correct,

2条回答
  •  臣服心动
    2020-12-18 12:33

    struct sockaddr_storage  *  peer_addr;
    
    
    getnameinfo((struct sockaddr *) &peer_add
                    peer_addrlen,
                    hostbuff, sizeof(hostbuff),
                    NULL, 0, NI_NAMEREQD);
    

    Here you are mixing up stuff.

    getnameinfo() indeed takes a struct sockaddr* as its first parameter, but what you try to do here won't work: peer_addr is a struct sockaddr_storage *, you take its address - which is a struct sockaddr_storage **, and try to cast this. That won't work.

    I don't know where your peer_addr comes from, but

    • either it should be a struct sockaddr_storage (I don't think there is a need to have a pointer to a struct sockaddr_storage somewhere)
    • or it is really a pointer, and you should pass (struct sockaddr *) peer_addr - without the & - to getnameinfo().

    Another point: The second parameter for getnameinfo() is supposed to be the "real" size of the address struct you are inputting.

提交回复
热议问题