#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <net/if.h>
#include <arpa/inet.h>
#define ERRORIP "cannot find host ip"
char *ip_search(void)
{
int sfd, intr;
struct ifreq buf[16];
struct ifconf ifc;
sfd = socket (AF_INET, SOCK_DGRAM, 0);
if (sfd < 0)
return ERRORIP;
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t)buf;
if (ioctl(sfd, SIOCGIFCONF, (char *)&ifc))
return ERRORIP;
intr = ifc.ifc_len / sizeof(struct ifreq);
while (intr-- > 0 && ioctl(sfd, SIOCGIFADDR, (char *)&buf[intr]));
close(sfd);
return inet_ntoa(((struct sockaddr_in*)(&buf[intr].ifr_addr))-> sin_addr);
}
int main(void)
{
printf("%s\n", ip_search());
return 0;
}
linux 下获取本机IP
最新推荐文章于 2023-08-31 12:47:01 发布
本文介绍了一个使用C语言编写的程序,该程序通过系统调用获取本地主机的IP地址。程序利用了socket编程的相关API,包括socket、ioctl等,并通过SIOCGIFCONF和SIOCGIFADDR请求来枚举并获取网络接口及其对应的IP地址。
1240

被折叠的 条评论
为什么被折叠?



