Reputation: 14179
Is it possible to extract the destination and source IP addresses in the following case? I was able to extract Ethernet source and destination addresses from in_buffer
. Any suggestion if it is possible to do it?
sockaddr_ll sockaddr = sockaddr_ll();
sockaddr.sll_family = PF_PACKET;
sockaddr.sll_protocol = htons(ETH_P_ALL);
// is the interface index of the interface
sockaddr.sll_ifindex = if_nametoindex(argv[1]);
sockaddr.sll_hatype = 1;
boost::asio::io_service io_service;
raw_protocol_t::socket socket(io_service, raw_protocol_t(PF_PACKET, SOCK_RAW));
socket.bind(raw_endpoint_t(&sockaddr, sizeof(sockaddr)));
boost::asio::generic::raw_protocol::socket::receive_buffer_size option;
socket.get_option(option);
std::string in_buffer(option.value(), '\0');
raw_endpoint_t rep = raw_endpoint_t();
while (true)
{
size_t len = socket.receive_from(boost::asio::buffer(&in_buffer[0], in_buffer.size()), rep);
}
Upvotes: 3
Views: 2538
Reputation: 3360
Yes, you can read IP address from the raw packet buffer. Of course only if there is an IP address in the packet. The data stored in the in_buffer
contains complete packet including IP header if the protocol is IP.
Note the received data may contain any protocol. It can be IPv4 and then you can find IP addresses there but it can be IPv6 or even more obscure protocol without IP addresses.
Let assume the received packet is an Ethernet-II
packet containing IPv4
data. Then you can easily get IP addresses:
// Source addr
printf("%d.%d.%d.%d", (unsigned char)(in_buffer[26]),
(unsigned char)(in_buffer[27]),
(unsigned char)(in_buffer[28]),
(unsigned char)(in_buffer[29]));
// Destination addr
printf("%d.%d.%d.%d", (unsigned char)(in_buffer[30]),
(unsigned char)(in_buffer[31]),
(unsigned char)(in_buffer[32]),
(unsigned char)(in_buffer[33]));
Sure it is not nice and you need check if the buffer contains what is expected but it is up to you.
And what does the magic number means 26 - 32?
The Ethernet II header has size 14 bytes. First 6 bytes are destination MAC, next 6 bytes are source MAC and the last 2 bytes ethertype. Ethertype 0x0800 means the data contain IPv4. The source IPv4 address is at offset 12 in IP header and the destination IP is at offset 16. So the magic number 26 means offset from packet begin and its 14(ethernetHeaderSize) + 12(offsetInIPHeader).
Upvotes: 1