Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"lvalue required as unary '&' operand" in accept() socket system call

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?

like image 571
nikos Avatar asked Dec 12 '22 12:12

nikos


2 Answers

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];
like image 123
CB Bailey Avatar answered Jan 17 '23 06:01

CB Bailey


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]});
like image 30
R.. GitHub STOP HELPING ICE Avatar answered Jan 17 '23 04:01

R.. GitHub STOP HELPING ICE