获取本机IP

   之前用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);
//接下来一个一个的获取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;
}
//——————————-函数的调用方式————————————-

char ip[20];

if ( getlocalip( ip ) == 0 )
{
printf( “ 本机IP地址是: %s\n”, ip );
}
else
{
printf( ” 无法获取本机IP地址  ” );
}

posted on 2012-04-18 18:42 Marv 阅读(508) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔档案

文章分类

搜索

最新评论

阅读排行榜

评论排行榜