26.07.2018 Views

hacking-the-art-of-exploitation

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A simple example will suffice for now. When dealing with many time functions,<br />

<strong>the</strong>se functions use a time struct called tm, which is defined in /usr/include/<br />

time.h. The struct’s definition is as follows.<br />

struct tm {<br />

int tm_sec; /* seconds */<br />

int tm_min; /* minutes */<br />

int tm_hour; /* hours */<br />

int tm_mday; /* day <strong>of</strong> <strong>the</strong> month */<br />

int tm_mon; /* month */<br />

int tm_year; /* year */<br />

int tm_wday; /* day <strong>of</strong> <strong>the</strong> week */<br />

int tm_yday; /* day in <strong>the</strong> year */<br />

int tm_isdst; /* daylight saving time */<br />

};<br />

After this struct is defined, struct tm becomes a usable variable type, which<br />

can be used to declare variables and pointers with <strong>the</strong> data type <strong>of</strong> <strong>the</strong> tm struct.<br />

The time_example.c program demonstrates this. When time.h is included,<br />

<strong>the</strong> tm struct is defined, which is later used to declare <strong>the</strong> current_time and<br />

time_ptr variables.<br />

time_example.c<br />

#include <br />

#include <br />

int main() {<br />

long int seconds_since_epoch;<br />

struct tm current_time, *time_ptr;<br />

int hour, minute, second, day, month, year;<br />

seconds_since_epoch = time(0); // Pass time a null pointer as argument.<br />

printf("time() - seconds since epoch: %ld\n", seconds_since_epoch);<br />

time_ptr = &current_time; // Set time_ptr to <strong>the</strong> address <strong>of</strong><br />

// <strong>the</strong> current_time struct.<br />

localtime_r(&seconds_since_epoch, time_ptr);<br />

// Three different ways to access struct elements:<br />

hour = current_time.tm_hour; // Direct access<br />

minute = time_ptr->tm_min; // Access via pointer<br />

second = *((int *) time_ptr); // Hacky pointer access<br />

}<br />

printf("Current time is: %02d:%02d:%02d\n", hour, minute, second);<br />

The time() function will return <strong>the</strong> number <strong>of</strong> seconds since January 1,<br />

1970. Time on Unix systems is kept relative to this ra<strong>the</strong>r arbitrary point in<br />

time, which is also known as <strong>the</strong> epoch. The localtime_r() function expects two<br />

pointers as arguments: one to <strong>the</strong> number <strong>of</strong> seconds since epoch and <strong>the</strong><br />

o<strong>the</strong>r to a tm struct. The pointer time_ptr has already been set to <strong>the</strong> address<br />

Programming 97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!