Skip to content

Instantly share code, notes, and snippets.

@oakaigh
Forked from javiermon/LICENSE
Created January 3, 2019 00:42
Show Gist options
  • Save oakaigh/e3f7dd1d6f6415bc378dfd0f300cc66d to your computer and use it in GitHub Desktop.
Save oakaigh/e3f7dd1d6f6415bc378dfd0f300cc66d to your computer and use it in GitHub Desktop.
get default gateway
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <net/if.h>
#define BUFFER_SIZE 4096
int getgatewayandiface(in_addr_t * addr, char *interface)
{
long destination, gateway;
char iface[IF_NAMESIZE];
char buf[BUFFER_SIZE];
FILE * file;
memset(iface, 0, sizeof(iface));
memset(buf, 0, sizeof(buf));
file = fopen("/proc/net/route", "r");
if (!file)
return -1;
while (fgets(buf, sizeof(buf), file)) {
if (sscanf(buf, "%s %lx %lx", iface, &destination, &gateway) == 3) {
if (destination == 0) { /* default */
*addr = gateway;
strcpy(interface, iface);
fclose(file);
return 0;
}
}
}
/* default route not found */
if (file)
fclose(file);
return -1;
}
int main(int argc, char **argv)
{
in_addr_t addr = 0;
char iface[IF_NAMESIZE];
memset(iface, 0, sizeof(iface));
getgatewayandiface(&addr, iface);
printf("%s\n", inet_ntoa(*(struct in_addr *) &addr));
printf("%s\n", iface);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment