#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <string.h> int main() { struct ifaddrs* ifaddr = NULL; int ret = getifaddrs(&ifaddr); if (ret) { printf("getifaddrs failed, errno:%d\n", errno); return 1; } struct ifaddrs* ifp = ifaddr; char ip[16]; char netmask[16]; for ( ; ifp != NULL; ifp = ifp->ifa_next) { if (ifp->ifa_addr && ifp->ifa_addr->sa_family == AF_INET) { strncpy(ip, inet_ntoa(((struct sockaddr_in*)ifp->ifa_addr)->sin_addr), 16); strncpy(netmask, inet_ntoa(((struct sockaddr_in*)ifp->ifa_netmask)->sin_addr), 16); printf("dev:%s, ip:%s, netmask:%s\n", ifp->ifa_name, ip, netmask); } } freeifaddrs(ifaddr); return 0; }
时间: 2024-11-05 21:34:57