=Start=
缘由:
项目需要
正文:
参考解答:
注意:当头文件include不全时可能会导致core dump,而且不易定位,所以建议在使用之前好好查一下需要包含的头文件列表。
#include <stdio.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <linux/netdevice.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #ifndef IP_LEN #define IP_LEN 256 #endif char ip[IP_LEN] = "\0" ; // AF_INET, AF_INET6 int print_addresses( const int domain) { int ssssss; ssssss = socket(domain, SOCK_STREAM, 0 ); if (ssssss < 0 ) { perror( "socket" ); return 1 ; } struct ifconf ifconf; struct ifreq ifr[ 50 ]; ifconf.ifc_buf = ( char *) ifr; ifconf.ifc_len = sizeof ifr; if (ioctl(ssssss, SIOCGIFCONF, &ifconf) == - 1 ) { perror( "ioctl" ); return 1 ; } char a_ip[INET_ADDRSTRLEN]; printf( "INET_ADDRSTRLEN = %d\n" , INET_ADDRSTRLEN); struct sockaddr_in *s_in; int ifs; ifs = ifconf.ifc_len / sizeof(ifr[ 0 ]); printf( "interfaces = %d:\n" , ifs); int i; for (i = 0 ; i < ifs; i++) { s_in = (struct sockaddr_in *) &ifr[i].ifr_addr; if (!inet_ntop(domain, &s_in->sin_addr, a_ip, sizeof(a_ip))) { perror( "inet_ntop" ); return 1 ; } printf( "%s - %s\n" , ifr[i].ifr_name, a_ip); if (strcmp(a_ip, "127.0.0.1" )) { printf( "strncat(*, *, %d)\n" , IP_LEN-strlen(ip)- 1 ); strncat(ip, a_ip, IP_LEN-strlen(ip)- 1 ); if (i+ 1 < ifs) { strcat(ip, "," ); } } } printf( "\nip = %s\n" , ip); close(ssssss); return 0 ; } int main( int argc, char const *argv[]) { print_addresses(AF_INET); return 0 ; } |
- socket+ioctl+inet_ntop
- getifaddrs()
- /proc/net/route
- strcat/strncat+strlen
参考链接:
- https://stackoverflow.com/questions/2021549/how-do-i-output-my-host-s-ip-addresses-from-a-c-program
- https://stackoverflow.com/questions/701004/how-to-get-ip-address-programmatically-on-debian-based-system
- http://man7.org/linux/man-pages/man3/getifaddrs.3.html
- =
- http://blog.csdn.net/ygm_linux/article/details/24661839
- http://walkerqt.blog.51cto.com/1310630/1741099
- http://blog.csdn.net/langeldep/article/details/8306603
- http://www.binarytides.com/get-local-ip-c-linux/
- =
- http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/ #gethostbyname() 或 getaddrinfo()
=END=