1.获取某个网卡的ip地址
#include <netinet/in.h> #include <net/if.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <string.h> #define ETH_NAME "wlan0" char* get_local_ip() { int sock; struct sockaddr_in sin; struct ifreq ifr; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { perror("socket"); return NULL; } strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ); ifr.ifr_name[IFNAMSIZ - 1] = 0; if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) { perror("ioctl"); return NULL; } memcpy(&sin, &ifr.ifr_addr, sizeof(sin)); return inet_ntoa(sin.sin_addr); } int main(void) { char* local_ip = get_local_ip(); printf("DEBUG:local_ip:%s\n", local_ip); return 0; }
此段代码可以获取Linux本地网卡的ip地址,wlan0可以修改成其他的网络设备。
标签:ifr,ip,网卡,Linux,include,local,sin From: https://www.cnblogs.com/zhuangquan/p/16854734.html