c - C 中的 UDP 套接字 - Sendto() 发送失败 : invalid arguments

标签 c sockets udp sendto

我正在尝试以非常简单/基本的方式在 C 中实现 UDP 套接字。我的程序旨在在终端之间发送/接收文件,每个终端上运行一个程序。我的客户端代码中的 sendto() 函数有问题。这是我的代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include <errno.h>

#define BUFFER_SIZE 512

int main(int argc, char *argv[])
{
    struct sockaddr_in client;
    int sockfd, bytes, errno, slen = sizeof(client);
    char buffer[BUFFER_SIZE];

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if(sockfd == -1)
    {
        perror("Socket creation failed.");
        return 0;
    }

    client.sin_addr.s_addr = INADDR_ANY;
    client.sin_family = AF_INET;
    client.sin_port = htons( 0 );

    if( bind(sockfd, (struct sockaddr *)&client, sizeof(client)) == -1)
    {
        perror("Bind call failed.");
        return 0;
    }

    while(1)
    {
        printf("Enter message : ");
        fgets(buffer, BUFFER_SIZE, stdin);

        printf("Message: %s\n", buffer);
        bytes = sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client));

        printf("Bytes: %d\n", bytes);

        if(bytes == -1)
        {
            printf("Error number: %d", errno);
            perror("Send failed.");
            return 0;
        }

        memset(buffer,'\0', BUFFER_SIZE);

        if( recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client, &slen) == -1)
        {
            perror("Recieve failed.");
            return 0;
        }

        puts(buffer);
    }

    close(sockfd);

    return 0;   
}

无论我向缓冲区输入什么,我总是从 sendto() 得到错误号 22 的无效参数。我已经尝试了我遇到的所有解决方案或调整,但似乎没有任何效果。

最佳答案

在bind()之后加入这段代码即可

getsockname(sockfd, (struct sockaddr *)&client, &slen);

手册页

 DESCRIPTION
     The getsockname() function returns the current address for the specified
     socket.

     The address_len parameter should be initialized to indicate the amount of
     space pointed to by address.  On return it contains the actual size of
     the address returned (in bytes).

     The address is truncated if the buffer provided is too small.

RETURN VALUES
     The getsockname() function returns the value 0 if successful; otherwise
     the value -1 is returned and the global variable errno is set to indicate
     the error.

关于c - C 中的 UDP 套接字 - Sendto() 发送失败 : invalid arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33046967/

相关文章:

android - PC服务器,安卓客户端。 UDP。客户端收不到服务器的数据包

jquery - 带有多个参数的 Json Post 请求

c - 嵌套时切换大小写

c - vc中的静态变量

php - 在 PHP 中启用输出缓冲检测用户中止

java - 无法使用 java Udp 获得响应

java - 如何混合来自 DatagramPackets 的多个实时语音音频流?

c - 获取 sizeof 可变数量的参数

macos - 无法取消链接套接字文件/tmp/mongodb-27017.sock errno :13 Permission denied

node.js - 套接字.io 1.0 : configure close timeout