You want to program at the kernel level and filter below the packet level but don't know how to open a file? You have ambitions.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
ssize_t bytes;
char buf[512];
int fd=open("path/to/file", O_RDONLY);
if(fd < 0)
{
perror("Couldn't open file");
return(1);
}
bytes=read(fd, buf, 512);
if(bytes <= 0)
{
perror("Couldn't read");
close(fd);
return(2);
}
close(file);
// You now have 'bytes' bytes of data read into the buffer 'buf'.
// Do other stuff here
return(0);
}
Thank you for your reply Corona688,
Haha it's not what you think, i learned RAW, TCP/IP and UNIX domain socket programming first because that's what i work with the most, but now i'm trying to learn FILE I/O and that's the reason of coding programs like this one.
You can also use "sendfile()". That's a lot more efficient because it cuts the number of memory copies by half.
When you read data from a file into the address space of a process, usually the data is copied into a kernel buffer as it comes in off disk, and it get copied again from that kernel buffer into the process buffer. To send that data out a socket, the data is first copied into a kernel buffer, and the data in that buffer is copied out to the socket.
The sendfile() library call will bypass the copying of data into and out of the address space of the process.
For example (I left off all error checking for clarity):
sendfile() is more efficient in some circumstances, but is also 100% linux-specific and nonportable, as well as subject to certain limitations -- the data source must be a file, and the destination must be a socket. It used to be less arbitrary, leading to a few bits of new code taking advantage of it breaking when this behavior was changed. I'm not sure if it behaves the same with all sockets or not, particularly raw sockets which as I understand it must be packet-based.