嵌入式使用小程序

2019-07-12 18:06发布

判断是否链接网线: #define NETCARD "eth0" struct ethtool_value{ __uint32_t cmd; __uint32_t data; }; int IsConnect_Router(void){ struct ethtool_value edata; //only pc has this struct , should define on ARM. int fd = -1, err = 0,temp; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, NETCARD); fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("Cannot get control socket"); return ERR; } edata.cmd = 0x0000000a; ifr.ifr_data = (caddr_t)&edata; err = ioctl(fd, 0x8946, &ifr); if (err == 0) { printf("connect:%d ",edata.data ? 1:0); temp = edata.data; } else if (errno != EOPNOTSUPP) { close(fd); perror("Cannot get link status"); return ERR; } close(fd); return temp; } 获取本地mac: #define NETCARD "eth0" int GetMacAddress(char* szmac ) { int sock_mac; struct ifreq ifr_mac; unsigned char mac[6]={0}; if(szmac == NULL) { return -1; } sock_mac = socket( AF_INET, SOCK_STREAM, 0 ); if( sock_mac == -1) { perror("create socket falise...mac/n"); return (-1); } memset(&ifr_mac,0,sizeof(ifr_mac)); strncpy(ifr_mac.ifr_name, NETCARD , sizeof(ifr_mac.ifr_name)-1); if( (ioctl( sock_mac, SIOCGIFHWADDR, &ifr_mac)) < 0) { perror("mac ioctl error:"); return (-1); } mac[0] = ifr_mac.ifr_hwaddr.sa_data[0]; mac[1] = ifr_mac.ifr_hwaddr.sa_data[1]; mac[2] = ifr_mac.ifr_hwaddr.sa_data[2]; mac[3] = ifr_mac.ifr_hwaddr.sa_data[3]; mac[4] = ifr_mac.ifr_hwaddr.sa_data[4]; mac[5] = ifr_mac.ifr_hwaddr.sa_data[5]; sprintf((char *)szmac,"%02X%02X%02X%02X%02X%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); close( sock_mac ); return 0; } 获取本机IP地址: #define IP_SIZE 16 int get_local_ip(const char *eth_inf, char *ip) { int sd; struct sockaddr_in sin; struct ifreq ifr; sd = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == sd) { printf("socket error: %s ", strerror(errno)); return -1; } strncpy(ifr.ifr_name, eth_inf, IFNAMSIZ); ifr.ifr_name[IFNAMSIZ - 1] = 0; if (ioctl(sd, SIOCGIFADDR, &ifr) < 0) { printf("ioctl error: %s ", strerror(errno)); close(sd); return -1; } memcpy(&sin, &ifr.ifr_addr, sizeof(sin)); snprintf(ip, IP_SIZE, "%s", inet_ntoa(sin.sin_addr)); close(sd); return 0; }