欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux系统下获取IP,MAC,子网掩码,网关

程序员文章站 2022-06-03 23:21:47
...

添加对应头文件

#include<stdio.h>
#include <cstdlib>
#include<string.h>
#include<unistd.h>
#include <fstream>
#include<iostream>
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <errno.h>
#include <linux/rtnetlink.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/utsname.h>
#include <limits.h>
#include <ctype.h>
#include <linux/sockios.h>

获取IP和子网掩码

int getLocalInfo(char IP[],char Mask[])
{
   int fd;
   int interfaceNum = 0;
   struct ifreq buf[16];
   struct ifconf ifc;
   struct ifreq ifrcopy;
   char mac[16] = {0};
   char ip[32] = {0};
   char broadAddr[32] = {0};
   char subnetMask[32] = {0};
   if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
   {
      perror("socket");
      close(fd);
      return -1;
   }
   ifc.ifc_len = sizeof(buf);
   ifc.ifc_buf = (caddr_t)buf;
   if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))
   {
      interfaceNum = ifc.ifc_len / sizeof(struct ifreq);
      printf("interface num = %d\n", interfaceNum);
      while (interfaceNum-- > 0)
      {
             printf("\ndevice name: %s\n", buf[interfaceNum].ifr_name);
             //ignore the interface that not up or not runing
             ifrcopy = buf[interfaceNum];
             if (ioctl(fd, SIOCGIFFLAGS, &ifrcopy))
             {
                printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
                close(fd);
                return -1;
             }
             //get the mac of this interface
             if (!ioctl(fd, SIOCGIFHWADDR, (char *)(&buf[interfaceNum])))
             {
                memset(mac, 0, sizeof(mac));
                snprintf(mac, sizeof(mac), "%02x%02x%02x%02x%02x%02x",
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[0],
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[1],
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[2],
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[3],
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[4],
                                (unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[5]);
                printf("device mac: %s\n", mac);
             }
            else
            {
                printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
                close(fd);
                return -1;
            }
            //get the IP of this interface
            if (!ioctl(fd, SIOCGIFADDR, (char *)&buf[interfaceNum]))
            {
                snprintf(ip, sizeof(ip), "%s",
                            (char *)inet_ntoa(((struct sockaddr_in *)&(buf[interfaceNum].ifr_addr))->sin_addr));
                printf("device ip: %s\n", ip);
            }
            else
            {
                printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
                close(fd);
                return -1;
            }
            //get the broad address of this interface
            if (!ioctl(fd, SIOCGIFBRDADDR, &buf[interfaceNum]))
            {
                snprintf(broadAddr, sizeof(broadAddr), "%s",
                            (char *)inet_ntoa(((struct sockaddr_in *)&(buf[interfaceNum].ifr_broadaddr))->sin_addr));
                printf("device broadAddr: %s\n", broadAddr);
            }
            else
            {
                printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
                close(fd);
                return -1;
            }
            //get the subnet mask of this interface
            if (!ioctl(fd, SIOCGIFNETMASK, &buf[interfaceNum]))
            {
                snprintf(subnetMask, sizeof(subnetMask), "%s",
                            (char *)inet_ntoa(((struct sockaddr_in *)&(buf[interfaceNum].ifr_netmask))->sin_addr));
                printf("device subnetMask: %s\n", subnetMask);
            }
            else
            {
                printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
                close(fd);
                return -1;
            }
        }
    }
    else
    {
        printf("ioctl: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
        close(fd);
        return -1;
    }
   strcpy(IP,ip);
   //strcpy(broad,broadAddr);
   strcpy(Mask,subnetMask);
   close(fd);
   return 0;
}

获取网关

int readNlSock(int sockFd, char *bufPtr, int seqNum, int pId)
{
      struct nlmsghdr *nlHdr;
      int readLen = 0, msgLen = 0;
      do{
            if((readLen = recv(sockFd, bufPtr, BUFSIZE - msgLen, 0)) < 0)
            {
              perror("SOCK READ: ");
              return -1;
            }

            nlHdr = (struct nlmsghdr *)bufPtr;
            if((NLMSG_OK(nlHdr, readLen) == 0) || (nlHdr->nlmsg_type == NLMSG_ERROR))
            {
              perror("Error in recieved packet");
              return -1;
            }
            if(nlHdr->nlmsg_type == NLMSG_DONE)
            {
              break;
            }
            else
            {

              bufPtr += readLen;
              msgLen += readLen;
            }
            if((nlHdr->nlmsg_flags & NLM_F_MULTI) == 0)
            {

             break;
            }
      } while((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != pId));
      return msgLen;
}

void parseRoutes(struct nlmsghdr *nlHdr, struct route_info *rtInfo,char gateway[])
{
      struct rtmsg *rtMsg;
      struct rtattr *rtAttr;
      int rtLen;
      char *tempBuf = NULL;
      struct in_addr dst;
      struct in_addr gate;
      tempBuf = (char *)malloc(100);
      rtMsg = (struct rtmsg *)NLMSG_DATA(nlHdr);
      // If the route is not for AF_INET or does not belong to main routing table
      //then return.
      if((rtMsg->rtm_family != AF_INET) || (rtMsg->rtm_table != RT_TABLE_MAIN))
      return;

      rtAttr = (struct rtattr *)RTM_RTA(rtMsg);
      rtLen = RTM_PAYLOAD(nlHdr);
      for(;RTA_OK(rtAttr,rtLen);rtAttr = RTA_NEXT(rtAttr,rtLen)){
       switch(rtAttr->rta_type) {
           case RTA_OIF:
            if_indextoname(*(int *)RTA_DATA(rtAttr), rtInfo->ifName);
            break;
           case RTA_GATEWAY:
            rtInfo->gateWay = *(u_int *)RTA_DATA(rtAttr);
            break;
           case RTA_PREFSRC:
            rtInfo->srcAddr = *(u_int *)RTA_DATA(rtAttr);
            break;
           case RTA_DST:
            rtInfo->dstAddr = *(u_int *)RTA_DATA(rtAttr);
            break;
       }
      }
      dst.s_addr = rtInfo->dstAddr;
      if (strstr((char *)inet_ntoa(dst), "0.0.0.0"))
      {
        printf("oif:%s",rtInfo->ifName);
        gate.s_addr = rtInfo->gateWay;
        sprintf(gateway, (char *)inet_ntoa(gate));
        printf("%s\n",gateway);
        gate.s_addr = rtInfo->srcAddr;
        printf("src:%s\n",(char *)inet_ntoa(gate));
        gate.s_addr = rtInfo->dstAddr;
        printf("dst:%s\n",(char *)inet_ntoa(gate));
      }
      free(tempBuf);
      return;
}

int get_gateway(char gateway[])
{
     struct nlmsghdr *nlMsg;
     struct rtmsg *rtMsg;
     struct route_info *rtInfo;
     char msgBuf[BUFSIZE];

     int sock, len, msgSeq = 0;

     if((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
     {
      perror("Socket Creation: ");
      return -1;
     }
     memset(msgBuf, 0, BUFSIZE);
     nlMsg = (struct nlmsghdr *)msgBuf;
     rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
     nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); // Length of message.
     nlMsg->nlmsg_type = RTM_GETROUTE; // Get the routes from kernel routing table .
     nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST; // The message is a request for dump.
     nlMsg->nlmsg_seq = msgSeq++; // Sequence of the message packet.
     nlMsg->nlmsg_pid = getpid(); // PID of process sending the request.
     if(send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0){
      printf("Write To Socket Failed…\n");
      return -1;
     }
     if((len = readNlSock(sock, msgBuf, msgSeq, getpid())) < 0) {
      printf("Read From Socket Failed…\n");
      return -1;
     }

     rtInfo = (struct route_info *)malloc(sizeof(struct route_info));
     for(;NLMSG_OK(nlMsg,len);nlMsg = NLMSG_NEXT(nlMsg,len)){
      memset(rtInfo, 0, sizeof(struct route_info));
      parseRoutes(nlMsg, rtInfo,gateway);
     }
     free(rtInfo);
     close(sock);
     return 0;
}