免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1493 | 回复: 2
打印 上一主题 下一主题

获取本地主机的IP地址 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-08-19 21:03 |只看该作者 |倒序浏览

                通过ioctl系统调用来实现本机指定网卡的IP地址。
               
               
                #include stdio.h>
#include stdlib.h>
#include string.h>
#include assert.h>
#include net/if.h>
#include netinet/in.h>
#include sys/socket.h>
#include sys/ioctl.h>
int getHostIP(char *ipaddr, int interface)
{
    int                 sockfd;
    struct ifreq        req;
   
    if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0))  0)
    {
        perror ("socket");
        return -1;
    }
   
    memset(&req, 0, sizeof(struct ifreq));
    sprintf(req.ifr_name, "eth%d", interface);
    // get current ip addr
    if (ioctl(sockfd, SIOCGIFADDR, (char*)&req))
    {
        perror(req.ifr_name);
        return -1;
    }
    else
    {
        struct in_addr ip_addr;
        char * tmpstr;
        ip_addr.s_addr = *((int*) &req.ifr_addr.sa_data[2]);
        tmpstr = inet_ntoa(ip_addr);
        strcpy(ipaddr, tmpstr);
    }
   
    close(sockfd);
   
    return 0;
}
int main(int argc, char **argv)
{
    char tmp_str[32];
    int interface = 0;
    if (argc > 1)
    {
        interface = atoi(argv[1]);
    }
   
    if (0 == getHostIP(tmp_str, interface))
    {
        printf("eth%d IP address is %s\n", tmp_str, interface);
    }
}
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/73948/showart_1134214.html

论坛徽章:
0
2 [报告]
发表于 2008-08-22 21:25 |只看该作者
看不懂,那些编程的语言,继续学习中!!!

论坛徽章:
0
3 [报告]
发表于 2008-08-22 21:39 |只看该作者
原帖由 libiao.yu 于 2008-8-19 21:03 发表

                通过ioctl系统调用来实现本机指定网卡的IP地址。
               
               
                #include stdio.h>
#include stdlib.h>
#include string.h>
#include assert.h>
#include net/if.h>
#include netinet/in.h>
#include sys/socket.h ...



应该可以得到 多网卡 的 ip 地址吧?
!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP