简体   繁体   中英

BSD socket not working

UPDATE: src updated based on suggestions. strcat a \\n\\0 onto command and changing sizeof. Client has a "Succeed" on sending, but server never "succeeds" on receiving.

I have put a lot of working into trying to get a regular old TCP socket working. I basically have a simple client and a server setup. Currently I don't receive anything at all on my server, and I only get 4 bytes on my client ("GOTY" in this example).

Server output outputs this and moves on:

RECEIVED (null)

Client output just blocks and never stops. If I kill the server I get this output

Connect success
Received Response:

SERVER

int Server::update(char *getbuf)
{
    int ready = poll(pollfds, 1, 100);

    if (ready == -1)
    {
        logger.info("Poll failed");
        return FALSE;
    }

    if (pollfds[0].revents & POLLIN)
    {    
        ssize_t z;

        logger.info("Connection available");

        struct sockaddr_in client_address;
        memset(&client_address, 0, sizeof client_address);
        socklen_t alen = sizeof(client_address);

        // ACCEPT
        clientsocket = accept(serversocket, (struct sockaddr *)&client_address, &alen);
        if(!clientsocket)
            logger.fail("Accept Fail");

        // READ
        z = recv(clientsocket, getbuf, 512, MSG_WAITALL);
        if (z < 0)
            fprintf(stderr,"receive failure\n");
        else
            fprintf(stderr,"receive succeed\n");

        getbuf[z] = 0;

        respond(getbuf);

        //closeConnection();

        logger.data("RECEIVED %s", getbuf);

        getbuf[z] = 0;

        return TRUE;
    }

    return FALSE;
}

void Server::respond(char *response)
{
    // SEND
    ssize_t z;

    z = send(clientsocket, response, strlen(response), 0);
    if (z < 0)
        fprintf(stderr,"send failure\n");
    else
        fprintf(stderr,"send succeed\n");
}

CLIENT

I added the client code. I now use strlen but it doesn't seem to help things.

int main(int argc, char **argv)
{
    int abort = 0;
    int port;
    in_addr_t address;
    char *command;

    ssize_t z;
    int com_socket;
    struct sockaddr_in server_address;
    struct timeval timeout;

    int opt;
    int val = 0;
    char getbuf[512];

    //Defaults
    address = inet_addr("127.0.0.1");
    port = 4949;

    //INCLUDED ARGUMENTS FROM CLI
    while((opt = getopt(argc, argv, "a:p:c:")) > 0) 
    {
        switch(opt)
        {
            case 'a':
                address = inet_addr(optarg);
                break;
            case 'p':
                port = atoi(optarg);
                break;
            case 'c':
                abort = 1;
                command = (char *)optarg;
                break;   
            default:
                fprintf(stderr, "-a IPADDRESS -p PORT -c COMMAND\n",argv[0]);
        }
    }

    // Server
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(port);
    server_address.sin_addr.s_addr = address;

    if (server_address.sin_addr.s_addr == INADDR_NONE)
        fprintf(stderr, "Server address failed\n");

    if(!abort)
    {
        fprintf(stderr, "No Command given\n");
        fprintf(stderr, "-a IPADDRESS -p PORT -C COMMAND\n");
        exit(0);
    }
    else
    {
        fprintf(stderr, "Address %s Port %d Command %s\n", inet_ntoa(server_address.sin_addr), port, command);
    }

    // Create com_socket
    com_socket = socket(PF_INET, SOCK_STREAM, 0);
    if (com_socket == -1)
         fprintf(stderr, "Socket failed\n");

    /*
    // Client
    struct sockaddr_in client_address;
    memset(&client_address,0,sizeof client_address);
    client_address.sin_family = AF_INET;
    client_address.sin_port = 0;
    client_address.sin_addr.s_addr = ntohl(INADDR_ANY);

    if (client_address.sin_addr.s_addr == INADDR_NONE)
        fprintf(stderr, "Client address failed\n");

    // Bind
    z= bind(com_socket, (struct sockaddr *)&client_address, sizeof (client_address));
    if ( z == -1 )
        fprintf(stderr,"Binding port\n");
    */

    timeout.tv_sec = 2; /* 2 seconds */ 
    timeout.tv_usec = 0; /* + 0 usec */

    socklen_t addrlen = sizeof(struct sockaddr_in);

    // Connect
    //z = connectWithTimeout(com_socket, (struct sockaddr *) &server_address, len_inet, &timeout);
    z = connect(com_socket, (struct sockaddr *) &server_address, sizeof(server_address));
    if(z == -1)
    {
        if(errno == EINPROGRESS)
        {
            fprintf(stderr, "EINPROGRESS non block start\n");
        }

        if(errno == EALREADY)
        {
            fprintf(stderr, "EALREADY non block subsequent request\n");
        }

        fprintf(stderr, "Connect failed\n");
    }
    else 
        fprintf(stderr, "Connect success\n");

    strcat(command, "\n\0");

    // SEND
    z = send(com_socket, command, strlen(command)+2, 0);
    if (z < 0)
        fprintf(stderr,"send failure\n");
    else
        fprintf(stderr,"send succeed\n");

    // READ
    z = recv(com_socket, getbuf, 512, MSG_WAITALL);
    if (z < 0)
        fprintf(stderr,"receive failure\n");
    else
        fprintf(stderr,"receive succeed\n");

    // Output
    fprintf(stderr, "Received Response: %s\n", getbuf);

    close(com_socket);

    exit(1);
}

I just have no idea why this is not working. I've been over it again and again.

It's a embedded Linux system.

In the server: this is just plain wrong. strlen() returns the length of the string that was in the buffer before the read() /recv().

    // READ
    z = recv(clientsocket, getbuf, strlen(getbuf), MSG_WAITALL);
    if (z < 0)
        fprintf(stderr,"receive failure\n");

Also: in respond(), strlen() assumes that the response "string" is null-termated. It is not.

z = send(clientsocket, response, strlen(response), 0);

And the same type of error appears to be present in the client code.

UPDATE: since the OP does not know how to live without string functions, I'll illustrate how this could be done.

 ... snipped ...
 // READ
    z = recv(clientsocket, getbuf, 512, MSG_WAITALL);
    if (z < 0) {
        // .... if (errno == EAGAIN) continue;
        fprintf(stderr,"receive failure %d(%s) \n"
             , errno, strerror(errno) );
        break; }

    fprintf(stderr,"receive succeed\n");

    respond(getbuf, z);

    return TRUE;
    }
return FALSE;
}

void respond(char *response, size_t siz)
{
// SEND
size_t done;
ssize_t z;

for (done = 0; done < siz; done += z) { 
    z = send(clientsocket, response+done, siz-done, 0);
    if (z < 0) {
        if (errno == EAGAIN) continue;
        fprintf(stderr,"send failure %d(%s)\n"
           , errno, strerror(errno) );
        break; }
    fprintf(stderr,"send succeed\n");
    }
}

Since you have not actually shared the source of your "respond" function, my psychic powers tell me it looks something like this:

void Server::respond(char* str)
{
    send(clientsock, str, sizeof(str), 0);
}

As such, "sizeof(str)" is evaluating to 4 because that's the size of a pointer on your machine. That is consistent with the client receiving "GOTY" (the first 4 bytes of the message you intended to send).

Change it to the following:

void Server::respond(char* str)
{
    send(clientsock, str, strlen(str), 0);
}

Also, you should never assume that that send and recv will return a value equal to the amount of data you expected to send or receive. Hence, you should loop on non-blocking calls to send/recv until the entire message has been sent or consumed.

Send operations on sockets are often buffered so it's possible your respond function is not flushing all that data. Try a flush operation at the end of respond() to get the extra data.

It's looks to me like you're seeing blocking behaviour you might want to look into how blocking/non-blocking affects sockets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM