linux和Qt下获取本机每个接口的ip地址

#include <stdio.h>  
#include <sys/ioctl.h>  
#include <sys/socket.h>  
#include <sys/types.h>  
#include <netdb.h>  
#include <net/if.h>  
#include <arpa/inet.h>  
#define ERRORIP "cannot find host ip"  
char *ip_search(void)  
{  
    int sfd, intr;  
    struct ifreq buf[6];//最多6个网络接口  
    struct ifconf ifc;  
    sfd = socket (AF_INET, SOCK_DGRAM, 0);   
    if (sfd < 0)  
        return ERRORIP;  
    ifc.ifc_len = sizeof(buf);//先给一个大小,最后获得真实大小  
    ifc.ifc_buf = (caddr_t)buf;  
    if (ioctl(sfd, SIOCGIFCONF, (char *)&ifc))  
        return ERRORIP;  
    intr = ifc.ifc_len / sizeof(struct ifreq); //网络接口数量 
    while (intr-- > 0 && ioctl(sfd, SIOCGIFADDR, (char *)&buf[intr])); //获取每个接口的ip地址,结构为ifreq
    close(sfd);  
    return inet_ntoa(((struct sockaddr_in*)(&buf[intr].ifr_addr))-> sin_addr); //网络格式ip地址转成字符串格式 
}  
int main(void)  
{  
    printf("%s\n", ip_search());  
    return 0;  
} 
在Qt下,
foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()){
        qDebug()<<interface.name<<interface.hardwareAddress;
        foreach(QNetworkAddressEntry entry,interface.addressEntries()){
            qDebug()<<entry.ip()<<entry.netmask();
        }
}
或者直接调用QNetworkInterface::allAddress()返回本机所有ip地址。


你可能感兴趣的:(linux,linux,linux,socket,socket,socket,获取IP)