Jules
Jules

Reputation: 134

Retrieving source address in a recvmmsg UDP socket

I am receiving multiple messages through a socket using:

result = recvmmsg(socket_, &messages_[0], MAX_NUM_MSG, MSG_WAITFORONE, NULL);

And I want get the source address and port, but I am getting an error in the struct assignment when I try:

msg = &messages_[0];
***struct sockaddr *src = &msg->msg_hdr.msg_name;***

srcport = ntohs(src->sin_port);
srcaddr = ntohl(src->sin_addr.s_addr);

invalid conversion from ‘void**’ to ‘sockaddr*'

Upvotes: 1

Views: 937

Answers (1)

AllenLin
AllenLin

Reputation: 170

The recvmmsg system call is an extension of recvmsg. As described in recvmsg: The msg_name field points to a caller-allocated buffer that is used to return the source address

That means you should preallocate memory space for msg_name by yourself, and also you should specify msg_namelen, please try:

sockaddr_in addrs[MAX_NUM_MSG];
for (int i = 0; i < MAX_NUM_MSG; ++i) {
    messages_[i].msg_hdr.msg_name = &addrs[i];
    messages_[i].msg_hdr.msg_namelen = sizeof(sockaddr_in);
}

So that you can access address when you have at least one message by doing (Remember to use sockaddr_in but not sockaddr):

struct sockaddr_in *src = messages_[0].msg_hdr.msg_name;

Upvotes: 1

Related Questions