分类: LINUX
2011-06-18 10:42:50
/*根据接口名获取IP实例*/ #include #include #include #include #include #include #include #include #include #include #include #include int main(void) { int fd; struct ifreq ifr; struct sockaddr_in *sin; char LocalIP[32]; if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) { return -1; } memset(&ifr, 0, sizeof(struct ifreq)); ifr.ifr_addr.sa_family = AF_INET; strcpy(ifr.ifr_name, "eth0"); if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) { sin = (struct sockaddr_in *) &ifr.ifr_addr; strncpy(LocalIP, inet_ntoa(sin->sin_addr),16); } else { close(fd); return -1; } printf( "eth0 : %s\n", LocalIP ); close(fd); return 0; } Makefile: GetIPByIf : GetIPByIf.o gcc GetIPByIf.o -o GetIPByIf GetIPByIf.o : GetIPByIf.c gcc -c GetIPByIf.c .PHONY : clean clean: rm *.o GetIPByIf |
/*根据接口名获取子网掩码实例*/ #include #include #include #include #include #include #include #include #include #include #include #include int main(void) { int fd; struct ifreq ifr; struct sockaddr_in *sin; char LocalMask[32]; if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) { return -1; } memset(&ifr, 0, sizeof(struct ifreq)); ifr.ifr_addr.sa_family = AF_INET; strcpy(ifr.ifr_name, "eth0"); if (ioctl(fd, SIOCGIFNETMASK, &ifr) == 0) { sin = (struct sockaddr_in *) &ifr.ifr_netmask; strncpy(LocalMask, inet_ntoa(sin->sin_addr),16); } else { close(fd); return -1; } printf( "Mask of eth0 : %s\n", LocalMask ); close(fd); return 0; } Makefile: GetMaskByIf : GetMaskByIf.o gcc GetMaskByIf.o -o GetMaskByIf GetMaskByIf.o : GetMaskByIf.c gcc -c GetMaskByIf.c .PHONY : clean clean: rm *.o GetMaskByIf |