ifconfig
命令来获取本机 IP 地址。ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'
。在CLinux中获取本机IP地址有多种方法,以下是几种常见的方式:
使用系统调用和库函数
1、通过getifaddrs
函数:
这是一个较为常用的方法,首先需要包含相关的头文件,如<sys/types.h>
、<ifaddrs.h>
、<netinet/in.h>
、<arpa/inet.h>
等。
示例代码如下:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> int main() { struct ifaddrs *ifAddrStruct = NULL; struct ifaddrs *ifa = NULL; void *tmpAddrPtr = NULL; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); if (strcmp(ifa->ifa_name, "lo") != 0) { // exclude loopback interface printf("%s IP Address %s ", ifa->ifa_name, addressBuffer); } } } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); return 0; }
上述代码中,getifaddrs
函数会返回一个链表,其中包含了本机的所有网络接口信息,通过遍历这个链表,判断接口类型是否为AF_INET
(即IPv4地址),然后使用inet_ntop
函数将二进制的IP地址转换为点分十进制的字符串形式进行输出,同时排除了回环接口(通常名字为lo
)。
2、使用ioctl
函数:
先包含必要的头文件,如<sys/ioctl.h>
、<netinet/in.h>
、<net/if.h>
、<unistd.h>
、<arpa/inet.h>
等。
示例代码如下:
#include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <unistd.h> #include <arpa/inet.h> int get_localip(const char *eth_name, char *local_ip_addr) { int ret = -1; int fd; struct ifreq ifr; if (local_ip_addr == NULL || eth_name == NULL) { return ret; } if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) > 0) { strcpy(ifr.ifr_name, eth_name); if (!ioctl(fd, SIOCGIFADDR, &ifr)) { ret = 0; strcpy(local_ip_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); } } if (fd > 0) { close(fd); } return ret; } int main() { char local_ip[20] = {0}; if (get_localip("eth0", local_ip) == 0) { printf("local ip:%s ", local_ip); } else { printf("get local ip failure "); } return 0; }
这段代码中,首先创建一个套接字,然后通过ioctl
函数的SIOCGIFADDR
选项获取指定网络接口(这里是eth0
)的IP地址,并将其转换为字符串存储到local_ip
数组中,最后关闭套接字并返回结果。
使用命令行工具(在C程序中调用)
1、使用ifconfig
命令:
可以在C程序中使用system
函数调用ifconfig
命令来获取本机IP地址。
#include <stdlib.h> int main() { system("ifconfig"); return 0; }
执行上述代码后,会在终端中显示本机所有网络接口的详细信息,包括IP地址等,然后可以通过解析命令的输出来提取所需的IP地址信息。
2、使用ip
命令:
同样可以使用system
函数调用ip
命令,如:
#include <stdlib.h> int main() { system("ip addr"); return 0; }
ip addr
命令会显示更详细的网络接口信息,也可以从中解析出本机的IP地址。
3、使用hostname
命令:
#include <stdlib.h> int main() { system("hostname -I"); return 0; }
此命令会直接输出本机的IP地址,无需额外解析。
在CLinux中获取本机IP地址的方法有多种,开发者可以根据自己的需求和实际情况选择合适的方法来实现。
以上就是关于“clinux获取本机ip”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/808432.html