I am writing a network program where, in the server part, I want to accept connections from multiple clients using a listening socket. So I declare an array of address structs like this:
struct sockaddr_in* client;
which I create using malloc and later on, to accept connections I type:
newsock = accept(fd_skt, (struct sockaddr *)&client[i], &(sizeof(client[i])));
and there I get "lvalue required as unary '&' operand"
from the compiler. Can anyone figure out what I have done wrong?
Yes, you can't take the address of something that isn't an lvalue, that is an object with an address. The result of the sizeof
operator is just a value, it isn't an object with an address.
You need to create a local variable so that you can take its address.
E.g.
socklen_t addrlen = sizeof client[i];
newsock = accept(fd_skt, (struct sockaddr *)&client[i], &addrlen));
As an aside, struct sockaddr_in* client;
declares a pointer, not an array. To use client
as an array you need to assign it to a dynamically allocated array at some point before the call to accept
. I assume that this is what you are doing when you say "I create using malloc".
Alternatively you could actually declare client
as an array.
struct sockaddr_in client[MAX_CLIENTS];
Charles' answer is correct, but one way to get around this kind of obnoxious function interface that requires a pointer to a value you plan to just throw away is to use compound literals:
newsock = accept(fd_skt, (struct sockaddr *)&client[i], (socklen_t[]){sizeof client[0]});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With