Int get_gw (char * GW) {file * FP; char Buf [1024]; char cmd [1024]; char * TMP; strcpy (CMD, "IP Route "); fp = popen (CMD, "R"); If (null = FP) {perror ("popen error"); Return-1 ;}while (fgets (BUF, sizeof (BUF), FP )! = NULL) {TMP = Buf; while (* TMP & isspace (* TMP) + + TMP; If (strncmp (TMP, "default ", strlen ("default") = 0) break;} sscanf (BUF, "% * S % s", GW ); // filter the first two strings pclose (FP); Return 0 ;}
The gateway is obtained through the IP route command.
int get_mac_ip_mask(char *ifname,char *mac1,char *ip,char *mask){ int sock; struct ifreq ifr; unsigned char mac[6]; sock = socket(AF_INET,SOCK_STREAM,0); if(sock<0) { perror("socket error!\n"); return -1; } strcpy(ifr.ifr_name,ifname); if((ioctl(sock,SIOCGIFHWADDR,&ifr) )== 0) { memcpy(mac,ifr.ifr_hwaddr.sa_data,6); //printf("%s mac address is :%02X:%02X:%02X:%02X:%02X:%02X\n","eth0",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5] ); sprintf(mac1,"%02X-%02X-%02X-%02X-%02X-%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); } else { perror("ioctl error!\n"); return -1; } if((ioctl(sock, SIOCGIFADDR, &ifr)) == 0) { sprintf(ip,"%.15s", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr)); } else { perror("ioctl error!\n"); return -1; } if((ioctl( sock, SIOCGIFNETMASK, &ifr)) == 0) { //sprintf(ip,"%.15s", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr)); sprintf(mask, "%.15s",inet_ntoa((( struct sockaddr_in * )&( ifr.ifr_netmask ))->sin_addr)); } else { perror("ioctl error!\n"); return -1; } close(sock); return 0; }
Ifname indicates the network port eth0 .. Mac ip masks such as eth1 are obtained through the ioctl function.