使用gethostname() gethostbyname()等函数在Windows下去本机IP可以,但是到了Linux下就没用了:
char* getlocalhostip () { int MAXINTERFACES=16; char *ip=NULL; int fd, intrface, retn = 0; struct ifreq buf[MAXINTERFACES]; ///if.h struct ifconf ifc; ///if.h 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_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));//types break; } } } close (fd); } return ip; }