Linux下获取网卡IP,Netmask,Mac地址(gcc编译通过)

Linux下获取网卡IP,Netmask,Mac地址(gcc编译通过)

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>

int GetIP(const char *ifname, unsigned char *ip)
{
    int sock, ret;
    struct ifreq ifr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("socket");
        return -1;
    }

    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, ifname);

    ret = ioctl(sock, SIOCGIFADDR, &ifr, sizeof(ifr));
    if (ret == 0) {
        memcpy(ip, (&((struct sockaddr_in *)(&ifr.ifr_addr))->sin_addr), 4);
    } else {
        perror("ioctl");
    }
    close(sock);
    return ret;
}

int GetNetMask(const char *ifname, unsigned char *netmask)
{
    int sock, ret;
    struct ifreq ifr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror( "socket" );
        return -1;
    }

    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, ifname);
    ret = ioctl(sock, SIOCGIFNETMASK, &ifr, sizeof(ifr));
    if (ret == 0) {
        memcpy(netmask, (&((struct sockaddr_in *)(&ifr.ifr_netmask))->sin_addr), 4);
    } else {
        perror("ioctl");
    }
    close(sock);
    return ret;
}

int GetMac(const char *ifname, unsigned char *mac)
{
    int sock, ret;
    struct ifreq ifr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if ( sock < 0 ) {
        perror("socket");
        return -1;
    }

    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, ifname);
    ret = ioctl(sock, SIOCGIFHWADDR, &ifr, sizeof(ifr));
    if (ret == 0) {
        memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
    } else {
        perror("ioctl");
    }
    close(sock);
    return ret;
}

int main(int argc, char *argv[])
{
    int ret;
    char ifname[IFNAMSIZ];
    char ch[16];
    unsigned char ip[4];
    unsigned char netmask[4];
    unsigned char mac[6];

    if (argc == 1) {
        strcpy(ifname, "eth2");
    } else {
        strcpy(ifname, argv[1]);
    }

    memset(ip, 0, sizeof(mac));
    memset(netmask, 0, sizeof(mac));
    memset(mac, 0, sizeof(mac));

    ret = GetIP(ifname, ip);
    if (ret == 0) {
        printf("%s ip address is: %s\n", ifname, inet_ntop(AF_INET, ip, ch, 16));
    } else {
        fprintf(stderr, "Can't get %s's ip address\n", ifname);
    }

    ret = GetNetMask(ifname, netmask);
    if (ret == 0) {
        printf("%s netmask address is: %s\n", ifname, inet_ntop(AF_INET, netmask, ch, 16));
    } else {
        fprintf(stderr, "Can't get %s's netmask address\n", ifname);
    }

    ret = GetMac(ifname, mac);
    if (ret == 0) {
        printf("%s mac address is: [%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X]\n", ifname, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    } else {
        fprintf(stderr, "Can't get %s's mac address\n", ifname);
    }
    return 0;
}


你可能感兴趣的:(Linux下获取网卡IP,Netmask,Mac地址(gcc编译通过))