Linux C通过socket获取网络设备ip地址的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liusaoren/article/details/79962093


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

int get_ip(const char *ifname, char *ip)
{
    int sock_get_ip;
    int s32Ret = 0;
    char ipaddr[48];
    struct sockaddr_in *sin;
    struct ifreq_ifr;
    
    if((sock_get_ip = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        printf("socket create failed!\r\n");
        return -1;
    }
    
    memset(&ifr, sizeof(ifr));
    memcpy(ifr.ifr_name, ifname, strlen(ifname));
    
    if(ioctl(sock_get_ip, SIOCGIFADDR, &ifr) <0)
    {
        perror("ioctl error!\n");
        s32Ret = -2;
        goto FAILED;
    }
    
    sin = (struct sockaddr_in*)ifr.ifr_addr;
    if(NULL != ip) strcpy(ip, inet_ntoa(sin->sin_addr));
    
FAILED:
    close(sock_get_ip);
    return s32Ret;
}

int main(int argc, char *argv[])
{
    char ip[32] = { 0 };
    int s32Ret = 0;

    char *ifnet = "eth0";
    s32Ret = get_ip(ifnet, ip);
    printf("==ret:%d if:%s ip:%s==\n", s32Ret, ifnet, ip);

    ifnet = "lo";
    s32Ret = get_ip(ifnet, ip);
    printf("==ret:%d if:%s ip:%s==\n", s32Ret, ifnet, ip);
}


阅读更多

没有更多推荐了,返回首页