#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char hex2dec(unsigned char hex)
{
	hex = toupper(hex);
	hex -= (hex - 48 > 9) ? 55 : 48;
	return hex;
}

int hexstr_to_int(char *hex)
{
	int i, j;

	union {
		int l;
		unsigned char ch[4];
	} num;

	j = 0;
	for (i = 0; i < 8; i += 2)
		num.ch[j++] = hex2dec(hex[i]) * 16 + hex2dec(hex[i + 1]);

	return htonl(num.l);
}

char *get_gateway_str(void)
{
	FILE *fp;
	char *rt_file = "/proc/net/route";
	char str[256];

	char dst[9];
	char *dst_bgn;

	static char gw_str[9];
	char *gw_bgn;

	fp = fopen(rt_file, "r");
	if (fp == NULL) {
		printf("Cannot open file: %s\n", rt_file);
		perror("fopen()");
		exit(EXIT_FAILURE);
	}

	while (fgets(str, 255, fp) != NULL) {
		dst_bgn = strchr(str, '\11') + 1;
		memcpy(dst, dst_bgn, 8);
		dst[8] = '\0';
		if (strcmp(dst, "00000000") == 0) {
			gw_bgn = dst_bgn + 8 + 1;
			memcpy(gw_str, gw_bgn, 8);
		}
	}

	return gw_str;
}

int main()
{
	printf("%s", inet_ntoa(hexstr_to_int(get_gateway_str())));
	return 0;
}