问题
I'm trying to send a custom IPv6 header through a RAW socket in C Linux.
I already succeded in IPv4 using the IP_HDRINCL socket option, however, there's not an equivalent for IPv6.
I found a workaround here suggesting to use socket(AF_INET6, SOCK_RAW, IPPROTO_RAW)
to have the same effect as enabling the IP_HDRINCL socket option.
The socket is created successfully and I'm not getting any error until I use the sendto
function with my modified header.
I setup the socket like this:
static int socketFd = 0;
static struct sockaddr_in6 remote;
int main()
{
socketFd = socket (PF_INET6, SOCK_RAW, IPPROTO_RAW);
if (socketFd < 0)
{
printf ("An error ocurred while creating the socket.\n");
exit (2);
}
remote.sin6_family = AF_INET6;
remote.sin6_port = htons (25000);
if (inet_pton (AF_INET6, "fd00:c0de::70d6:4ab9:115d:8cda", &(remote.sin6_addr)) != 1)
{
close (socketFd);
printf ("Unable to parse IPv6 address.\n");
exit (2);
}
/*More code */
...
return 0;
}
And then, I have this callback function that should send my custom IPv6 packets but sendto
fails returning EINVAL.
static void sendPacket ()
{
char buffer[BUFSIZ];
const size_t len = sizeof(struct ip6_hdr) + sizeof(struct UDP_hdr);
struct ip6_hdr *ip6 = (struct ip6_hdr*) (buffer);
struct UDP_hdr *udp = (struct UDP_hdr *) (buffer + sizeof(struct ip6_hdr));
memset (buffer, 0, BUFSIZ);
ip6->ip6_ctlun.ip6_un2_vfc = 0x60;
ip6->ip6_dst = remote.sin6_addr;
ip6->ip6_flow = 60;
ip6->ip6_hops = 64;
ip6->ip6_nxt = 17;
ip6->ip6_plen = sizeof(struct UDP_hdr);
if (inet_pton (AF_INET6, "fd00:c0de::62a4:4cff:1234:5678", &(ip6->ip6_src)) != 1)
{
printf ("Error while parsing spoofed IPv6 address.\n");
return;
}
// Fabricate the UDP header. Source port number, redundant
udp->uh_sport = htons (21000);
// Destination port number
udp->uh_dport = remote.sin6_port;
udp->uh_ulen = htons (sizeof(struct UDP_hdr));
if (sendto (socketFd, buffer, len, 0, (struct sockaddr *) &remote, sizeof(remote)) < 0)
{
perror ("sendto");
printf ("Error while sending packet.\n");
}
}
I've debugged the program and all the values in the ip6_hdr struct seem to be correct and also the ones in the struct UDP_hdr. Am I missing something?
回答1:
Ok, so I found a solution. To anyone struggling with this, the way I solved it was using the Pcap library (followed this example). However for those that must use AF_PACKETS, I found a very complete example which uses RAW sockets to accomplish this in this link.
回答2:
To whom it may be helpful, I got a similar code to work, but opening the socket instead with
socket(test->state.addr_family, SOCK_RAW, IPPROTO_UDP);
Setting the options with
int val = 1; ret = setsockopt(test->state.sockfd, IPPROTO_IPV6, IPV6_HDRINCL, &val, sizeof (val));
and setting the port to zero with remote.sin6_port = 0;
, as explained in here to avoid the EINVAL
error on the sendto
call.
来源:https://stackoverflow.com/questions/31419727/how-to-send-modified-ipv6-packet-through-raw-socket