2012-01-05 wcdj
方法1:getaddrinfo
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>// inet_ntop #include <netdb.h> #include <string.h>// bzero #include <errno.h> void GetSelfServerIP(char *pszIP) { struct addrinfo *answer, hint, *curr; //char szIP[16]; bzero(&hint, sizeof(hint)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; int iRet = 0; char szHostName[128] = {0}; iRet = gethostname(szHostName, sizeof(szHostName)); if (iRet != 0) { fprintf(stderr, "gethostname error! [%s]\n", strerror(errno)); exit(1); } printf("hostname [%s]\n", szHostName); iRet = getaddrinfo(szHostName, NULL, &hint, &answer); if (iRet != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(iRet)); exit(1); } for (curr = answer; curr != NULL; curr = curr->ai_next) { inet_ntop(AF_INET, &(((struct sockaddr_in *)(curr->ai_addr))->sin_addr), pszIP, 16); //printf("%s\n", pszIP); } freeaddrinfo(answer); } int main(int argc, char **argv) { char szIP[16] = {0}; GetSelfServerIP(szIP); printf("IP [%s]\n", szIP); return 0; }
方法2:ioctl
#include <stdio.h> #include <stdlib.h> #include <unistd.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> bool GetLocalIP(char * pszIPBuf) { #define MAXINTERFACES 16 bool result = false; int fd = -1; int intrface = 0; struct ifreq buf[MAXINTERFACES]; struct ifconf ifc; 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); //根据借口信息循环获取设备IP和MAC地址 while (intrface-- > 0) { //获取设备名称 //printf ("net device %s\n", buf[intrface].ifr_name); if ( strstr(buf[intrface].ifr_name,"eth") != NULL ) { //获取当前网卡的IP地址 if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface]))) { if ( inet_ntop(AF_INET, &(( (struct sockaddr_in*)(& (buf[intrface].ifr_addr) ))->sin_addr), pszIPBuf,16) ) { return true; } } } } } close (fd); } return result; } int main() { char pszIPBuf[20] = {0}; GetLocalIP(pszIPBuf); if (pszIPBuf[0] != '\0') printf("local IP [%s]\n", pszIPBuf); else printf("Get local IP error!\n"); return 0; }