在 Linux 上获取接口的 IP 地址 [英] Get IP address of an interface on Linux
本文介绍了在 Linux 上获取接口的 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 C 代码获取 Linux 上接口的 IPv4 地址?>
例如,我想获取分配给 eth0 的 IP 地址(如果有).
解决方案
试试这个:
#include #include #include /* 对于 strncpy */#include #include #include #include #include #include 整数主要的(){国际金融;结构 ifreq ifr;fd = 套接字(AF_INET,SOCK_DGRAM,0);/* 我想获得一个 IPv4 IP 地址 */ifr.ifr_addr.sa_family = AF_INET;/* 我想要附加到eth0"的 IP 地址 */strncpy(ifr.ifr_name,eth0",IFNAMIZ-1);ioctl(fd, SIOCGIFADDR, &ifr);关闭(FD);/* 显示结果 */printf("%s
", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));返回0;}
代码示例取自此处.
How can I get the IPv4 address of an interface on Linux from C code?
For example, I'd like to get the IP address (if any) assigned to eth0.
解决方案
Try this:
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int
main()
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
printf("%s
", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return 0;
}
The code sample is taken from here.
这篇关于在 Linux 上获取接口的 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文