Linux环境下通过c代码获取本机IP
作者:网络转载 发布时间:[ 2014/4/17 9:44:37 ] 推荐标签:Linux 环境 代码
//接下来一个一个的获取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;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>
long getlocalhostip ()
{
int MAXINTERFACES = 16;
long ip;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
ip = -1;
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);
while (intrface-- > 0) {
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
ip = inet_addr (inet_ntoa (((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr));
break;
}
}
}
close (fd);
}
return ip;
}
union ipu
{
long ip;
unsigned char ipchar[4];
};
int main (int argc, char **argv)
{
union ipu localip;
localip.ip = getlocalhostip ();
printf ("local ip:%x :%u.%u.%u.%u
", localip.ip, localip.ipchar[0], localip.ipchar[1], localip.ipchar[2], localip.ipchar[3]);
return 0;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11