Linux环境下通过c代码获取本机IP

来源:互联网 发布:java目录遍历漏洞修复 编辑:程序博客网 时间:2024/04/29 06:56
之前用gethostname和gethostbyname获取本机IP地址运行没有问题,今天把程序部署到另一台机器上就出问题了。在网上找了些例子一样用不了。最后找了个能用的,创建一个SOCKET然后获取套接字参数。代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/types.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>

//获取地址
//返回IP地址字符串
//返回:0=成功,-1=失败
int getlocalip(char* outip)
{
int i=0;
int sockfd;
struct ifconf ifconf;
char buf[512];
struct ifreq *ifreq;
char* ip;
//初始化ifconf
ifconf.ifc_len = 512;
ifconf.ifc_buf = buf;

if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)
{
return -1;
}
ioctl(sockfd, SIOCGIFCONF, &ifconf);    //获取所有接口信息
close(sockfd);
//接下来一个一个的获取IP地址
ifreq = (struct ifreq*)buf;
for(i=(ifconf.ifc_len/sizeof(struct ifreq)); i>0; i–)
{
ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr);

if(strcmp(ip,”127.0.0.1″)==0)  //排除127.0.0.1,继续下一个
{
ifreq++;
continue;
}
strcpy(outip,ip);
return 0;
}

return -1;
}


 #include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>

long getlocalhostip ()
{
    int MAXINTERFACES = 16;
    long ip;
    int fd, intrface, retn = 0;
    struct ifreq buf[MAXINTERFACES];
    struct ifconf ifc;
    ip = -1;
    if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) {
        ifc.ifc_len = sizeof buf;
        ifc.ifc_buf = (caddr_t) buf;
        if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {
            intrface = ifc.ifc_len / sizeof (struct ifreq);
            while (intrface-- > 0) {
                if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
                    ip = inet_addr (inet_ntoa (((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr));
                    break;
                }
            }
        }
        close (fd);
    }
    return ip;
}

union ipu
{
    long ip;
    unsigned char ipchar[4];
};

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

0 0
原创粉丝点击