Tuesday, September 5, 2017

MIM'S - Extract IP address from buffer in C++ (Linux sockets)

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).

tuesday, 5th september, 9.20 am welcome back to war! the Hoa\Websocket\Server class allows to write a server manipulating the WebSocket protocol

Cielo e terra (duet with Dante Thomas)