Skip to content
Advertisement

accept(…) seems to be modifying the file descriptor parameter I give it

Here’s a section of my code, for a simple echo server I’m attempting to write using the linux sockets syscalls:

JavaScript

Just before this piece of code, I set up a socket descriptor fd, and then, immediately before the while loop begins:

JavaScript

I compile this and then run it, and then run a client program which I’ve written to send a message ("Hello from the client") to the server.

My problem

Anyway, my problem with this is that, as the title suggests, the call to accept(...) is modifying the value of fd. First of all, I can’t understand how this is possiblefd isn’t being passed as a pointer, so how could it possibly be modified by a function call? But this point is mainly just of interest – the main implication of this problem is described in the next section.

I’m certain the value of fd has been changed because here’s some sample output from the server:

JavaScript

So as you can see, fd before the call to accept is 3, but then after the call it becomes 0.

Why this is a problem

Referring back to the output from the server, as shown above:

JavaScript

Which clearly is as a result of the new value of fd not being a valid socket.

What I’ve tried

Enveloping also the listen(...) call in the while(true) {...} loop, just in case I need to listen again for each client. I doubted this would work, and it didn’t. I’m all out of ideas.

Other questions which haven’t helped

I found a question somewhere asking why accept(...) was returning (not changing the fd parameter) a value of 0. I understand from that that 0 is a valid socket descriptor, but clearly here it isn’t. Also, this just shouldn’t be happening, right?

My question

Just to sum up: why is accept(...) modifying one of its non-pointer parameters, and how can I fix this?

Full code

JavaScript

Advertisement

Answer

Your code has undefined behavior, as expected.

JavaScript

First off, you are taking address of addr, which is already a pointer. You should not do this.

Also, my little crystal ball tells me you are on 64 bit platform, and as such, your socklen_t is a 64bit integer.

To fix your problems, do not take address of the pointer and do away with nasty cast and use the proper type.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement