c++获取本机ip地址

来源:互联网 发布:卷积神经网络算法流程 编辑:程序博客网 时间:2024/05/17 00:15

c实现主要是依赖于两个结构体

struct ifreq {
#define IFHWADDRLEN 6
union
{
char ifrn_name[IFNAMSIZ];/* if name, e.g. "en0" */
} ifr_ifrn;

union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct  sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct  ifmap ifru_map;
char ifru_slave[IFNAMSIZ];/* Just fits the size */
char ifru_newname[IFNAMSIZ];
void * ifru_data;
struct if_settings ifru_settings;
} ifr_ifru;
};


struct ifconf  {
int ifc_len;/* size of buffer*/
union {
char *ifcu_buf;
struct ifreq *ifcu_req;
} ifc_ifcu;
};
#define ifc_bufifc_ifcu.ifcu_buf/* buffer address*/
#define ifc_reqifc_ifcu.ifcu_req/* array of structures*/

这两个结构体在if.h中

find /usr/include -name "*.h" -exec grep -l "ifconf" {} \; 找到此文件

网友实例:

#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>#include <iostream>using namespace std;const int  MAXINTERFACES=16;long getlocalhostip(){long ip;int fd, intrface, retn = 0;struct ifreq buf[MAXINTERFACES]; ///if.hstruct ifconf ifc; ///if.hip = -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, SIOCGIFADDR, (char *) &buf[intrface]))){ip=inet_addr( inet_ntoa( ((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr) );//typesbreak;}           }}close(fd);}return ip;}union ipu{long ip;unsigned char ipchar[4];};int main(int argc, char **argv){union ipu iptest;iptest.ip = getlocalhostip();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;}

实例二:

include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/ioctl.h>#include <netinet/in.h>#include <net/if.h>#include <net/if_arp.h>#include <arpa/inet.h>#include <errno.h>#include <iostream>#include <string.h>using namespace std;int getlocalip(char *localip);int main()  {              char localip[30];getlocalip(localip);cout << localip << endl;return 0;}int getlocalip(char *localip){const char* eth0="eth0";int sock;struct sockaddr_in sin;          struct ifreq ifr;sock = socket(AF_INET, SOCK_DGRAM, 0);if (sock == -1){perror("socket");return -1;}strncpy(ifr.ifr_name, eth0, IFNAMSIZ);ifr.ifr_name[IFNAMSIZ - 1] = 0;if (ioctl(sock, SIOCGIFADDR, &ifr) < 0){perror("ioctl");return -1;}memcpy(&sin, &ifr.ifr_addr, sizeof(sin));strcpy(localip ,inet_ntoa(sin.sin_addr));}

实例三:

int getlocalip(char* outip){int i=0;int sockfd;struct ifconf ifconf;char buf[512];struct ifreq *ifreq;char* ip;//初始化ifconfifconf.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;}

实例四, 使用shell获取本机IP

string GetLocalIpAddress(){    FILE *fp = NULL;    char buff[256];    string strIP = "N/A";    int i;    if(0 == system("ifconfig | grep 'Bcast'| tr -s ' ' : | cut -d: -f4 > /tmp/ip.lst"))    {        fp = fopen("/tmp/ip.lst", "rt");        if(fp)        {            if(fgets(buff, 256, fp) > 0)            {                for(i = strlen(buff) - 1; i >= 0; i--)                {                    if(buff[i] != '\x0A' && buff[i] != '\x0D')                    {                        buff[i + 1] = '\0';                        break;                    }                }                strIP = buff;            }            fclose(fp);        }    }    return strIP;}

或者:

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>int main(int argc, char *argv[]){const char* shellstr = "ifconfig | sed -n '2p' | awk -F'[ :]+' '{printf $4}'";    FILE *fp = popen(shellstr, "r");char line[20];memset(line, 0, sizeof(line));    fgets(line, 20, fp);puts(line);    return 0;}


0 0
原创粉丝点击