Linux环境下通过c代码获取本机IP

发表于:2014-4-17 10:46

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:linuxheik    来源:51Testing软件测试网采编

  之前用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);
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号