linux用popen获取ip地址和mac地址

直接上代码

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

 int hex2num(char c)
 {
     if (c>='0' && c<='9') return c - '0';
     if (c>='a' && c<='z') return c - 'a' + 10;//这里+10的原因是:比如16进制的a值为10
     if (c>='A' && c<='Z') return c - 'A' + 10;
     
    // printf("unexpected char: %c", c);
     return -1;
 }
  


 #define ETH_NAME "ens33"
int GetLocalIp(char *localIp, unsigned char len)
{
    
    FILE *fp;
    char buf[256] = {0};
    char command[256] = {0};
    //char *fmt = "ifconfig %s|sed -n '2p'|sed -n 's#^.*dr:##gp'|sed -n 's#B.*$##gp'";//| awk -F '\n' '{print $0}'
    char *fmt = "ifconfig %s|grep 'inet '|awk '{ print $2}'  ";
 
    snprintf(command, sizeof(command), fmt, ETH_NAME);
    //printf("%s", command);
    if((fp = popen(command, "r")) == NULL)
    {
        perror("Fail to popen\n");
        return -1;
    }
    while(fgets(buf, sizeof(buf), fp) != NULL)
    {
        printf("%s", buf);
    }
    pclose(fp);
     int i=strlen(buf);
    if(i>strlen("255.255.255.255"))
        return -1;
    buf[i-1]='\0';//去掉"\n"
    
    
    snprintf(localIp, len, "%s", buf);
    return 0;
}

int GetMacAddr(unsigned char *mac, unsigned char len)
{

    FILE *fp;
    char buf[256] = {0};
    char command[256] = {0};
    //char *fmt = "ifconfig %s|sed -n '2p'|sed -n 's#^.*dr:##gp'|sed -n 's#B.*$##gp'";
    char *fmt = "ifconfig %s|grep 'ether'|awk '{ print $2}' ";
 
    snprintf(command, sizeof(command), fmt, ETH_NAME);
    if((fp = popen(command, "r")) == NULL)
    {
        perror("Fail to popen\n");
        return -1;
    }
    while(fgets(buf, sizeof(buf), fp) != NULL)
    {
        printf("%s", buf);
    }
 
    pclose(fp);
    char i=0;
    char j=0;
    for(i=0;i<strlen(buf);i++){
        int ret;
        ret=hex2num(buf[i]);
        if(ret!=-1){
            if(j%2)
                mac[j/2] |=ret;
            else
                mac[j/2] |= ret<<4;
            j++;
        }
    }
    //printf( "%02x:%02x:%02x:%02x:%02x:%02x", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
    return 0;
}


int main()
{
    char buf[128]={0};
    
    GetLocalIp(buf,128);
    printf("Ip:[%s]\n",buf);
    
    unsigned char mac[6]={0};
    GetMacAddr(mac,6);
    printf( "mac:[%02x:%02x:%02x:%02x:%02x:%02x]\n", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值