-1

So I'm doing some client server stuff here, and I want my server to listen for clients, and when a client connects to the server, the client sends a string. The connection establishes, the clients sends it's string, but, at server side, recv() returns -1.

/* Server */
int main() {

 int fd, conn_fd; 
 struct sockaddr_in ad; 
 int bytes; 
 char recv_buffer[256];

 fd = socket(AF_INET, SOCK_STREAM, 0); 
 ad.sin_family = AF_INET;
 ad.sin_port = htons(3335); 
 ad.sin_addr.s_addr = htonl(INADDR_ANY);

 bind(fd, (struct sockaddr*)&ad, sizeof(ad)); 
 listen(fd, 5);

 conn_fd = accept(fd, (struct sockaddr*)0, 0); 
 bytes = recv(fd, recv_buffer, sizeof(recv_buffer), 0); 
 printf("%d\n", bytes);

 return 0;

}

The clients simply connects to the server: /* Client */

int main() {
    int fd, n;
    unsigned int s;
    struct sockaddr_in addr;
    fd = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(3335);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    char buff[256] = "time";

    printf("Connecting to server....\n");
    if(connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        printf("connect() error.\n");
        exit(1);
    }

    s = send(fd, buff, sizeof(buff), 0);    

    return 0;
}

Thanks!

  • 1
    When `recv` returns `-1`, it's because an error happened. Check the `errno` variable for more information about the error. http://man7.org/linux/man-pages/man3/errno.3.html The list of the errors from `recv` are listed here : http://man7.org/linux/man-pages/man2/recv.2.html – Maxime Alvarez Dec 04 '16 at 15:33
  • 1
    Call `perror` if `recv` returns -1. That will tell you *why* it failed. Also, you should add error checking to all socket functions, with a call to `perror` in the error case. – dbush Dec 04 '16 at 15:33
  • 2
    It could have something to do with you not receiving on the correct socket. – Some programmer dude Dec 04 '16 at 15:34
  • OK, I will do that, thanks, guys! – EQ_ALL_THE_WAY Dec 04 '16 at 15:34
  • It seems that errno = 107 (Transport endpoint is not connected). Any idea what the problem might be? – EQ_ALL_THE_WAY Dec 04 '16 at 15:46
  • 1
    How can you possibly know that `send()` sent when you don't check the return value? How do you know you even got a socket in the first place? You need to error-check all of `socket(), listen(), bind(), accept(), connect(), send(),` and `recv()`. – user207421 Dec 04 '16 at 17:09

1 Answers1

0

I found out what the problem was. In my server code, I was using the wrong socket descriptor for recv(): instead of fd, I should have used conn_fd.