Code for obtaining the Mac subnet mask of the local gateway IP address in Linux

Source: Internet
Author: User
Tags socket error
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.