在Linux环境下使用C语言获取IP地址,可以通过以下几种方法:
getifaddrs
函数getifaddrs
函数可以获取系统中所有网络接口的信息,包括IP地址。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if_link.h>
void get_ip_addresses() {
struct ifaddrs *ifaddr, *ifa;
int family, s;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6) {
s = getnameinfo(ifa->ifa_addr,
(family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
ifa->ifa_name, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s
", gai_strerror(s));
continue;
}
printf("%s: %s
", ifa->ifa_name, ifa->ifa_name);
}
}
freeifaddrs(ifaddr);
}
int main() {
get_ip_addresses();
return 0;
}
ioctl
函数ioctl
函数可以通过套接字接口获取网络接口信息。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
void get_ip_addresses() {
int sockfd;
struct ifconf ifc;
char buf[1024];
int success = 0;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) {
perror("ioctl(SIOCGIFCONF)");
exit(EXIT_FAILURE);
}
struct ifreq *it = ifc.ifc_req;
const struct ifreq *const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
char hostname[NI_MAXHOST];
if (getnameinfo(it->ifr_addr,
sizeof(struct sockaddr_in),
hostname, NI_MAXHOST,
NULL, 0, NI_NUMERICHOST) == 0) {
printf("%s: %s
", it->ifr_name, hostname);
}
}
close(sockfd);
}
int main() {
get_ip_addresses();
return 0;
}
sudo
命令运行程序。通过以上方法,可以在Linux环境下使用C语言获取系统的IP地址。
领取专属 10元无门槛券
手把手带您无忧上云