0

I'm actually back to programming in C, and I want to code a UDP Client.

My problem is that I'm having an error when executing the sendto function... getting errno : 22 and the message error : Invalid argument

char query[1024];
int querySize = strlen(query);

SOCKADDR_IN dest = { 0 };
int destSize = sizeof dest;

dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr('192.168.0.3');
dest.sin_port = htons(6000);

sendto(sock, query, querySize, 0, (SOCKADDR *) &dest, destSize)

Hope someone could help me?

Here is my full code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#if defined (WIN32)
    #include <winsock2.h>
    typedef int socklen_t;
#elif defined (linux)
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>

    #define INVALID_SOCKET -1
    #define SOCKET_ERROR -1
    #define closesocket(param) close(param)

    typedef int SOCKET;
    typedef struct sockaddr_in SOCKADDR_IN;
    typedef struct sockaddr SOCKADDR;
#endif

int main(int argc, char *argv[]) {
    #if defined (WIN32)
        WSADATA WSAData;
        WSAStartup(MAKEWORD(2,2), &WSAData);
    #endif

    char source_ip[15] = "192.168.0.20";
    int source_port = 5000;

    char query[1024];

    printf("- Opening Socket\n");
    SOCKET sock;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock == INVALID_SOCKET) {
        perror("[ERROR] socket()");
        exit(errno);
    }

    printf("- Configuring socket source to : [%s:%d]\n", source_ip, source_port);
    SOCKADDR_IN source;
    source.sin_family = AF_INET;
    source.sin_addr.s_addr = inet_addr(source_ip);   
    source.sin_port = htons(source_port);
    if(bind(sock, (SOCKADDR *)&source, sizeof(source)) == SOCKET_ERROR) {
        perror("[ERROR] bind()");
        exit(errno);
    }

    int querySize = strlen(query);
    SOCKADDR_IN dest = { 0 };
    int destSize = sizeof dest;
    dest.sin_family = AF_INET;

    printf("- Sending packets\n");
    dest.sin_addr.s_addr = inet_addr('192.168.0.3');
    dest.sin_port = htons(6000);

    if(sendto(sock, query, querySize, 0, (SOCKADDR *) &dest, destSize) < 0) {
        perror("[ERROR] sendto()");
        printf("%d\n", errno);
        exit(errno);
    }

    printf("\n\n##############################\n");
    printf("Closing socket ...\n");
    closesocket(sock);

    #if defined (WIN32)
        WSACleanup();
    #endif

    printf("Program finished.\n");
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
McH
  • 9
  • 2

1 Answers1

0

Did you notice, that query is not being initialized? So strlen(query) might result in a "very long" buffer. That would be a good candidate for an EINVAL.

rpy
  • 3,953
  • 2
  • 20
  • 31