Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdint.h>
- #define IP_HEADER_MIN_SIZE 20
- #define IP_HEADER_MAX_SIZE 60
- struct ip_header
- {
- unsigned int version:4;
- unsigned int ihl:4;
- uint8_t tos;
- uint16_t tot_len;
- uint16_t id;
- uint16_t frag_off;
- uint8_t ttl;
- uint8_t protocol;
- uint16_t check;
- uint32_t saddr;
- uint32_t daddr;
- // IP options starts here
- };
- struct udp_header
- {
- uint16_t uh_sport;
- uint16_t uh_dport;
- uint16_t uh_ulen;
- uint16_t uh_sum;
- // UDP payload starts here
- };
- /* Build a UDP/IP packet and store it into buffer passed as parameter */
- void new_packet(char *buf, char *options, int optsize, int udp_udp_size) {
- int i;
- int ip_header_size = optsize + sizeof(struct ip_header); /* compute total IP header size, from option size */
- struct ip_header *ip = (void*) buf;
- for (i = 0 ; i < optsize; i++)
- buf[i + sizeof(struct ip_header)] = options[i];
- ip->ihl = ip_header_size >> 2; /* put correct header size in ip header */
- struct udp_header *udp = (void*)buf + ip_header_size; /* udp headers starts immediately after ip header end */
- udp->uh_ulen = udp_udp_size; /* put udp payload size in udp header */
- // Initialization of irrelevant fields (source/destination IP, ports, etc) have been omitted.
- }
- void raw_socket_write(char *data, int size) {
- // Write to raw socket (omitted)
- }
- void send_packet(char *buf) {
- struct ip_header *h1 = (void*) buf;
- int header_size = h1->ihl << 2; /* get ip header size */
- struct udp_header *h2 = (void*) buf + header_size; /* udp header starts immediately after ip header end */
- int udp_size = h2->uh_ulen; /* get udp payload size from udp header */
- int i;
- uint32_t checksum = 0;
- // compute UDP checksum
- for (i = 0; i < udp_size; i++) {
- // Actual checksum computation omitted
- }
- h2->uh_sum = checksum;
- raw_socket_write(buf, header_size + udp_size);
- }
- #define PAYLOAD_MIN_SIZE 16
- #define PAYLOAD_MAX_SIZE 1024
- int send_request_over_udp(char *options, int optsize, int udpsize) {
- char buf[1024];
- int i;
- if ((optsize + sizeof(struct ip_header) >= IP_HEADER_MIN_SIZE) &&
- (optsize + sizeof(struct ip_header) <= IP_HEADER_MAX_SIZE) &&
- (udpsize + sizeof(struct udp_header) >= PAYLOAD_MIN_SIZE) &&
- (udpsize + sizeof(struct udp_header) <= PAYLOAD_MAX_SIZE))
- {
- /* sizes are in acceptable range */
- new_packet(buf, options, optsize, udpsize);
- // Create packet payload here (omitted)
- // ...
- send_packet(buf);
- } else {
- return -1; // Error
- }
- }
- int main(void) {
- char options[1024];
- int optsize, udpsize;
- send_request_over_udp(options, optsize, udpsize);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement