Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <net/if.h>
- #include <arpa/inet.h>
- #include <string.h>
- #define __sockaddr_in(x) ((struct sockaddr_in *)(x))
- struct in_addr get_host_ip(const char *ifname)
- {
- int rval;
- int sock;
- struct ifreq ifr;
- struct in_addr error = {
- .s_addr = 0,
- };
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock == -1)
- return error;
- memset(&ifr, '\0', sizeof(ifr));
- strncpy(ifr.ifr_name, ifname, strlen(ifname));
- rval = ioctl(sock, SIOCGIFADDR, &ifr);
- if (rval)
- return error;
- return __sockaddr_in(&ifr.ifr_addr)->sin_addr;
- }
- struct in_addr get_host_netmask(const char *ifname)
- {
- int rval;
- int sock;
- struct ifreq ifr;
- struct in_addr error = {
- .s_addr = 0,
- };
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock == -1)
- return error;
- memset(&ifr, '\0', sizeof(ifr));
- strncpy(ifr.ifr_name, ifname, strlen(ifname));
- rval = ioctl(sock, SIOCGIFNETMASK, &ifr);
- if (rval)
- return error;
- return __sockaddr_in(&ifr.ifr_netmask)->sin_addr;
- }
- struct in_addr get_host_default_gw(void)
- {
- FILE *fp;
- char line[BUFSIZ];
- unsigned long gw;
- unsigned long dest;
- struct in_addr rval = {
- .s_addr = 0,
- };
- fp = fopen("/proc/net/route", "r");
- if (!fp)
- return rval;
- while (fgets(line, BUFSIZ, fp)) {
- char *ptr = strchr(line, '\t');
- if (!ptr)
- return rval;
- sscanf(ptr, "%x", &gw);
- if (gw == 0) {
- ptr = strchr(++ptr, '\t');
- if (!ptr)
- return rval;
- sscanf(ptr, "%x", &dest);
- if (dest) {
- rval.s_addr = dest;
- return rval;
- }
- }
- }
- return rval;
- }
- int main(void)
- {
- printf("NETMASK: %s\n", inet_ntoa(get_host_ip("eth0")));
- printf("IP: %s\n", inet_ntoa(get_host_netmask("eth0")));
- printf("DEFAULT GW: %s\n", inet_ntoa(get_host_default_gw()));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement