之前用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); |