EFAULT when trying to send char

320 Views Asked by At

I am trying to send a single 1 byte value using send however when I try to it fails and sets errno to EFAULT. I am unsure why this is as I am setting the buf argument to the address of the char.

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

There are 1 best solutions below

1
On BEST ANSWER

The problem is that you are creating a raw socket. That means you have to create the full IP packet from scratch to send, which you do not do.

What happens right now is undefined behavior as the send call and the underlying network stack goes out of bounds reading data beyond the single byte you provide.