How can you get a raw socket in Perl, and then what's the best way to built a packet for use with it?
The basic call to get a socket is... socket(). It comes standard with perl 5. perl 5 basically gives you the standard socket(), bind(), listen(), accept() calls that traditional UNIX does.
For a more object oriented model, check out IO::Socket.
The same way you do in C... by setting the socket type when creating the socket.
In the example on CPAN use SOCK_RAW rather than SOCK_DGRAM (UDP) or SOCK_STREAM (TCP).
NOTE: creating raw sockets typically requires administrative privileges (i.e. root on UNIX). Windows OS's may have disabled ability to create raw sockets, you'll just have to test it and see.
Looks like Net::RawIP was what I was looking for:
use Net::RawIP;
$a = new Net::RawIP;
$a->set({ip => {saddr => 'my.target.lan',daddr => 'my.target.lan'},
tcp => {source => 139,dest => 139,psh => 1, syn => 1}});
$a->send;
$a->ethnew("eth0");
$a->ethset(source => 'my.target.lan',dest =>'my.target.lan');
$a->ethsend;
$p = $a->pcapinit("eth0","dst port 21",1500,30);
$f = dump_open($p,"/my/home/log");
loop $p,10,\&dump,$f;
As austirg and others said, Socket will do this just fine:
use Socket;
socket my $socket, PF_INET, SOCK_RAW, 0 or die "Couldn't create raw socket: $!";
send $socket, $message, $flags, $to or die "Couldn't send packet: $!";
my $from = recv $socket, $message, $length, $flags or die "Couldn't receive from socket: $!";
At first I was thinking that most previous answers were not responsive to the question. After further thought, I think the author is probably not asking the right question.
If you're writing an application, you don't usually think of "building packets". you just open sockets, format up the data payload, and it's the protocol stack that builds packets with your data. OK, if you're using datagrams, you do need to define, generate and parse your payloads. But you typically let the kernel encapsulate it at the network level (e.g. add IP header) or link layer (e.g. add Ethernet framing). You usually don't use pcap. Sometimes just pack and unpack and maybe vec is enough.
If you're writing an unusual packet processor such as an active hostile attack tool, a man-in-the-middle process, or a traffic shaping device, then would be more likely to be "building packets" and using pcap. Maybe Net::Packet is for you also.