dhcp/udp4.cpp

42 lines
1.3 KiB
C++

#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include "ip4.h"
#include "udp4.h"
namespace udp4 {
header * make_header(void * buf,
uint32_t source_port,
uint32_t destination_port,
uint32_t source_address,
uint32_t destination_address,
void const * payload,
int payload_length)
{
memset(buf, 0, (sizeof (header)));
header * hdr = reinterpret_cast<header *>(buf);
hdr->source_port = source_port;
hdr->destination_port = destination_port;
hdr->length = htons(payload_length + (sizeof (header)));
ip4_psuedo_header phdr;
phdr.source_address = source_address;
phdr.destination_address = destination_address;
phdr.zeros = 0;
phdr.protocol = ip4::protocol::udp;
phdr.udp_length = hdr->length; // already big endian
uint32_t sum = 0;
sum = ip4::checksum_partial(sum, reinterpret_cast<void const *>(&phdr), (sizeof (ip4_psuedo_header)));
sum = ip4::checksum_partial(sum, reinterpret_cast<void const *>(hdr), (sizeof (header)));
sum = ip4::checksum_partial(sum, reinterpret_cast<void const *>(payload), payload_length);
hdr->checksum = htons(ip4::checksum_finish(sum));
return hdr;
}
}