1

I'm trying to reuse connected socket fd.

I've created connfd and connected it to the server in initialisation code. And in some other function, I do not reconnect it again, but try connfd directly..

On server,

connfd = accept(listenfd, (struct sockaddr *)&cliAddr, &len);
recvfrom(connfd, msg, TCP_DATA_LEN, 0, (struct sockaddr *)&cliAddr, &len);

On client,

sendto(sockfd, messageString, strlen(messageString), 0, (struct sockaddr *)&servAddr, sizeof(servAddr));

sockfd is from

socket(AF_INET, SOCK_STREAM, 0);
connect(sockfd, (struct sockaddr *)&servAddr, sizeof(servAddr));

But on the server, I do not receive anything.

1
  • "reuse connected socket fd" -- please tell us more about what that means, exactly. Can you show even more context than this? Also, why is it important to you to reuse the socket fd?
    – Brian Cain
    Apr 6, 2015 at 16:50

2 Answers 2

1

did the code for each apply 'connect()' to their respective sockets?

the server needs to first accept() then listen() where listen() will return a new socket.

That new socket is what is used to recv() from the client.

recvfrom() and sendto() are for datagram (UDP) sockets not SOCK_STREAM (TCP) sockets.

so the code should use send() and recv().

suggest reading the man pages for the system functions the code uses

here is a link to an example, Note the example spawns a thread to handle the connection. for a single connection, the thread is not necessary.

http://www.mycplus.com/source-code/c-source-code/tcp-client-and-server/

0

sendto and recvfrom are for use with non-connection oriented sockets (SOCK_DGRAM rather than SOCK_STREAM), and may fail with EISCONN if you use them on connected sockets. Even if they work, the extra arguments are meaningless, so there's never any reason to use them on a connected socket.

Just use send and recv on connected sockets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.