在C中编码UDP套接字 - 发送到无效参数

时间:2016-03-01 10:07:26

标签: sockets udp errno sendto

我实际上回到使用C编程,我想编写一个 UDP客户端

我的问题是,我在执行 sendto 功能时遇到错误...获取错误:22 并且消息错误:参数无效

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)

希望有人可以帮助我?

这是我的完整代码:

#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;
}

1 个答案:

答案 0 :(得分:0)

你注意到了, 该查询未初始化? 因此strlen(查询)可能会导致“非常长”的缓冲区。 那将是EINVAL的一个很好的候选人。