EFAULT 尝试发送字符时

EFAULT when trying to send char

我正在尝试使用 send 发送单个 1 字节值,但是当我尝试发送时它失败并将 errno 设置为 EFAULT。我不确定为什么会这样,因为我将 buf 参数设置为字符的地址。

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <unistd.h>

#define INVALID_SOCKET ~0

int main()
{
    int s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    struct sockaddr_in sin = {0};
    char C0 = 3;

    if(s == INVALID_SOCKET){exit(1);}

    sin.sin_addr.s_addr = inet_addr(/*ip*/);
    sin.sin_port        = htons(1935);
    sin.sin_family      = AF_INET;

    printf("Destination IP: %s\n", inet_ntoa(sin.sin_addr));
    printf("Destination Port: %u\n", ntohs(sin.sin_port));

    if(connect(s, (struct sockaddr*)&sin, sizeof(sin)) == -1){printf("Errno: %d\n", errno);exit(2);}

    if(send(s, &C0, 1, 0) == -1)
    {
        switch(errno)
        {
            case EFAULT:
            {
                printf("Error: Invalid memory address\nExiting\n");
                close(s);
                exit(3);
                break;
            }
            default:
            {
                printf("Error: %d\nExiting\n", errno);
                close(s);
                exit(3);
                break;
            }
        }
    }

    return 0;
}

问题是您正在创建 raw 套接字。这意味着您必须从头开始创建完整的 IP 数据包才能发送,而您不需要这样做。

现在发生的是 未定义的行为,因为 send 调用和底层网络堆栈越界读取超出您提供的单个字节的数据。