2
votes

I'm trying to write a simple UDP socket client-server program. The client machine is supposed to send a string to the server, that will answer with an ACK message.

Here's the implementation of the client side:

int main() {
    message_send('L');
    return EXIT_SUCCESS;
}


int message_send(char code) {
    int sockfd;
    ssize_t n;
    char recvline[MAXLINE + 1];
    struct sockaddr_in servaddr;
    // Create an UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return -1;
    }

    // Setup the socket
    memset((void *) &servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = (in_port_t) htonl(SERV_PORT);
    if (inet_pton(AF_INET, SERVIP, &servaddr.sin_addr) <= 0) {
        fprintf(stderr, "Error in inet_pton for %s\n", SERVIP);
        exit(1);
    }

    // Send a test string
    char *test = malloc(MAXLINE);
    snprintf(test, MAXLINE, "SENDING:%c", code);
    if (sendto(sockfd, &test, sizeof(test), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
        perror("sendto");
        return -1;
    }

    // Get an answer from the server
    n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
    if (n < 0) {
        perror("recvfrom");
        exit(1);
    } else if (n > 0) {
        recvline[n] = 0; // Add ending character
        if (fputs(recvline, stdout) == EOF) { // Print the received message in stdout
            perror("fputs");
            return -1;
        }
    }
    return 0;
}

If I run this (whether the server machine is running or not) I get the following error:

sendto: Invalid argument

Why am I getting this error?

1
@user3386109 thanks for your answer, that solved my issue - Robb1
@user3386109: Why not make this an answer? - alk
@user3386109 indeed, this could be useful as a duplicate. - Antti Haapala
Ok, I converted the comment to an answer. - user3386109

1 Answers

1
votes

The most likely cause of the problem is the line

servaddr.sin_port = (in_port_t) htonl(SERV_PORT);

I'm guessing that gives you a bad port number (i.e. it will give you port 0 on a little endian machine). Port numbers are 16-bit, so you should be using htons.

Also, passing &test and sizeof(test) to sendto will send the pointer value over the network. To send the string, you need to use test and strlen(test)+1.