linux编程--c代码获取本机IP地址

       通过脚本获取本机IP很容易,当我们写一些逻辑复杂的应用时,就需要考虑类似如下的方式了,下面的方式不一定是最好的,供有需要的博友以参考。


一、编写代码

/*

* create by  bdkyr

*date 2015-1-22

*/

#include <stdio.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>

#include <sys/ioctl.h>
#include <linux/if.h>

long getlocalhostip(char *dev_name){
    int  MAXINTERFACES=16;
    long ip;
    int fd, intrface, retn = 0;
    struct ifreq buf[MAXINTERFACES]; ///if.h
    struct ifconf ifc; ///if.h
    ip = -1;
    if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h
    {
        ifc.ifc_len = sizeof(buf);
        ifc.ifc_buf = (caddr_t) buf;
        if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) //ioctl.h
        {
            intrface = ifc.ifc_len / sizeof (struct ifreq);
            while (intrface-- > 0)
            {
                if (ioctl(fd, SIOCGIFFLAGS, (char *) &buf[intrface]))
                {
                    continue;
                }
                if (buf[intrface].ifr_flags & IFF_LOOPBACK)
                    continue;
                if (!(buf[intrface].ifr_flags & IFF_UP))
                    continue;
                if (ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))
                {
                    continue;
                }
                //char* dev_name="em1";
                if (dev_name != NULL && strcmp(dev_name, buf[intrface].ifr_name))
                    continue;
                if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface])))
                {
                    close(fd);
                    return ((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr.s_addr;
                }

            }
        }
        close (fd);
    }
    return 0;
}
union ipu{
    long ip;
    unsigned char ipchar[4];
};

int main(int argc, char **argv){
    union ipu iptest;
    iptest.ip = getlocalhostip(argv[1]);
    printf("local ip:%x :%3u.%3u.%3u.%3u \n",iptest.ip, iptest.ipchar[0],iptest.ipchar[1],iptest.ipchar[2],iptest.ipchar[3]);
    return 0;

}

二、编译

[root@test bdkyr]# gcc get_local_ip.c -o get_local_ip

三、运行

[root@test bdkyr]# ./get_local_ip em1
local ip:c9c8a8c0 :192.168.200.201

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值