user1601045
user1601045

Reputation: 59

cpp Linux socket programming error with accept

This is my first linux socket program. I am using the server client model. I have read tutorials and created both the server and the client. But I am having a problem with the server side code.

I receive this error message at the accept line "invalid conversion for 'int*' to 'socklen_t* {aka unsigned int*}'".
How can I fix this issue? Below is the server code.

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>

using namespace std;
#define MAX_SIZE 50

int main()
{
    int sock_descriptor, conn_desc;
    struct sockaddr_in serv_addr, client_addr;
    char buff[MAX_SIZE];
    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_descriptor < 0)
        cout << "Failed creating socket" << endl;
    bzero((char *)&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(1234);

    if(bind(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        cout << "Failed to bind" << endl;

    listen(sock_descriptor, 5);
    cout << "Waiting for connection...\n" << endl;

    int size = sizeof(client_addr);
    conn_desc = accept(sock_descriptor, (struct sockaddr *)&client_addr, &size);
    if(conn_desc == -1)
        cout << "Failed accepting connection" << endl;
    else
        cout << "Connected" << endl;

    if(read(conn_desc, buff, sizeof(buff)-1) > 0)
        cout << "Received %s" << buff << endl;
    else
        cout << "Failed receiving" << endl;

    close(conn_desc);
    close(sock_descriptor);

    return 0;
}

Upvotes: 1

Views: 2935

Answers (2)

MK.
MK.

Reputation: 34597

Perhaps you should declare size as

socklen_t size;

Upvotes: 0

DS.
DS.

Reputation: 24170

Replace

int size = sizeof(client_addr);

with

socklen_t size = sizeof(client_addr);

Upvotes: 4

Related Questions