获取本机ip和网卡mac等信息的代码

来源(ChinaUnix.net)

From: http://bbs.chinaunix.net/viewthread.php?tid=85716&extra=page%3D1%26filter%3Ddigest###

获取本机ip和网卡mac等信息的代码


所以最终版本是下面这个
solaris上编译方式是:
gcc getip.c -DSOLARIS -lsocket -lnsl

linux直接用
gcc getip.c

#include <stdio.h>;
#include <sys/types.h>;
#include <sys/param.h>;

#include <sys/ioctl.h>;
#include <sys/socket.h>;
#include <net/if.h>;
#include <netinet/in.h>;
#include <net/if_arp.h>;

#ifdef SOLARIS
#include <sys/sockio.h>;
#endif

#define MAXINTERFACES   16

main (argc, argv)
register int argc;
register char *argv[];
{
   register int fd, intrface, retn = 0;
   struct ifreq buf[MAXINTERFACES];
   struct arpreq arp;
   struct ifconf ifc;

   if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >;= 0) {
      ifc.ifc_len = sizeof buf;
      ifc.ifc_buf = (caddr_t) buf;
      if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {
         intrface = ifc.ifc_len / sizeof (struct ifreq);
         printf("interface num is intrface=%d\n\n\n",intrface);
         while (intrface-- >; 0)
          {
            printf ("net device %s\n", buf[intrface].ifr_name);

/*Jugde whether the net card status is promisc  */
            if (!(ioctl (fd, SIOCGIFFLAGS, (char *) &buf[intrface]))) {
               if (buf[intrface].ifr_flags & IFF_PROMISC) {
                  puts ("the interface is PROMISC");
                  retn++;
               }
            } else {
               char str[256];

               sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
               perror (str);
            }

/*Jugde whether the net card status is up       */
            if (buf[intrface].ifr_flags & IFF_UP) {
                puts("the interface status is UP");
               }
            else {
                puts("the interface status is DOWN");
            }

/*Get IP of the net card */
            if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
                {
                 puts ("IP address is:");
                 puts(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->;sin_addr));
                 puts("");
                   //puts (buf[intrface].ifr_addr.sa_data);
                }
            else {
               char str[256];

               sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
               perror (str);
           }
/* this section can't get Hardware Address,I don't know whether the reason is module driver*/
//          ((struct sockaddr_in*)&arp.arp_pa)->;sin_addr=((struct sockaddr_in*)(&buf[intrface].ifr_addr))->;sin_addr;
#ifdef SOLARIS
            arp.arp_pa.sa_family = AF_INET;
            arp.arp_ha.sa_family = AF_INET;
            ((struct sockaddr_in*)&arp.arp_pa)->;sin_addr.s_addr=((struct sockaddr_in*)(&buf[intrface].ifr_addr))->;sin_addr.s_addr;
            if (!(ioctl (fd, SIOCGARP, (char *) &arp)))
                {
                 puts ("HW address is:");

                 printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
                                (unsigned char)arp.arp_ha.sa_data[0],
                                (unsigned char)arp.arp_ha.sa_data[1],
                                (unsigned char)arp.arp_ha.sa_data[2],
                                (unsigned char)arp.arp_ha.sa_data[3],
                                (unsigned char)arp.arp_ha.sa_data[4],
                                (unsigned char)arp.arp_ha.sa_data[5]);

                 puts("");
                 puts("");
                }


#else
#if 0
/*Get HW ADDRESS of the net card */
            if (!(ioctl (fd,  SIOCGENADDR, (char *) &buf[intrface])))
                {
                 puts ("HW address is:");

                 printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
                                (unsigned char)buf[intrface].ifr_enaddr[0],
                                (unsigned char)buf[intrface].ifr_enaddr[1],
                                (unsigned char)buf[intrface].ifr_enaddr[2],
                                (unsigned char)buf[intrface].ifr_enaddr[3],
                                (unsigned char)buf[intrface].ifr_enaddr[4],
                                (unsigned char)buf[intrface].ifr_enaddr[5]);

                 puts("");
                 puts("");
                }
#endif
            if (!(ioctl (fd, SIOCGIFHWADDR, (char *) &buf[intrface])))
                {
                 puts ("HW address is:");

                 printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[0],
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[1],
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[2],
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[3],
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[4],
                                (unsigned char)buf[intrface].ifr_hwaddr.sa_data[5]);

                 puts("");
                 puts("");
                }
#endif

            else {
               char str[256];

               sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
               perror (str);
           }
        }
      } else
         perror ("cpm: ioctl");

   } else
      perror ("cpm: socket");

    close (fd);
    return retn;
}



看到另外一个网上资料,solaris下说可以用直接访问dlpi api的方式可以取到mac地址。我贴过来了,各位试试看。
http://groups.google.com/groups?hl=zh-CN&lr=&ie=UTF-8&oe=UTF-8&frame=right&th=4e11f68182497875&seekm=tardp79vv9o9d3%40corp.supernews.com#link2


/*
* mac_addr_dlpi.c
*
* Return the MAC (ie, ethernet hardware) address by using the dlpi api.
*
* compile with: gcc -c -D "OS" mac_addr_dlpi.c
* with "OS" is one of AIX, SunOS, HPUX
*/

/**********************************************************************/
/* this section defines a list of the dlpi capable devices
* this depends on the operating system
*/

#undef DLPI_DEV

#ifdef HPUX
static char *dlpi_dev[] = {"/dev/dlpi", ""};
#define DLPI_DEV
#endif

#ifdef AIX
static char *dlpi_dev[] = {"/dev/dlpi/et", "/dev/dlpi/en",
"/dev/dlpi/tr", "/dev/dlpi/fddi", ""};
#define DLPI_DEV
/* AIX: remember to set up /etc/pse.conf or /etc/dlpi.conf */
#endif

#ifdef SunOS
static char *dlpi_dev[] = {"/dev/hme", "/dev/ie", "/dev/le", ""};
#define DLPI_DEV
#endif

#ifndef DLPI_DEV
static char *dlpi_dev[] = {"/dev/dlpi", ""};
/* unknown OS - hope that this will work ??? */
#define DLPI_DEV
#endif

/**********************************************************************/
/*
* implementation
*/

#define INSAP 22
#define OUTSAP 24

#include <sys/types.h>;
#include <fcntl.h>;
#include <errno.h>;
#include <stdio.h>;
#include <string.h>;
#include <signal.h>;
#include <ctype.h>;
#include <sys/stropts.h>;
#include <sys/poll.h>;
#include <sys/dlpi.h>;

#define bcopy(source, destination, length) memcpy(destination, source, length)

#define AREA_SZ 5000 /*&=&* buffer length in bytes *&=&*/
static u_long ctl_area[AREA_SZ];
static u_long dat_area[AREA_SZ];
static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area};
static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area};
#define GOT_CTRL 1
#define GOT_DATA 2
#define GOT_BOTH 3
#define GOT_INTR 4
#define GOT_ERR 128

/*&=&* get a message from a stream; return type of message *&=&*/
static int get_msg(int fd)
{
    int flags = 0;
    int res, ret;
    ctl_area[0] = 0;
    dat_area[0] = 0;
    ret = 0;
    res = getmsg(fd, &ctl, &dat, &flags);
    if(res < 0) {
        if(errno == EINTR) {
            return(GOT_INTR);
        } else {
            return(GOT_ERR);
        }
    }
    if(ctl.len >; 0) {
        ret |= GOT_CTRL;
    }
    if(dat.len >; 0) {
        ret |= GOT_DATA;
    } return(ret);
}

/*&=&* verify that dl_primitive in ctl_area = prim *&=&*/
static int check_ctrl(int prim)
{
    dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
    if(err_ack->;dl_primitive != prim) {
        return GOT_ERR;
    } return 0;
}

/*&=&* put a control message on a stream *&=&*/
static int put_ctrl(int fd, int len, int pri)
{
    ctl.len = len;
    if(putmsg(fd, &ctl, 0, pri) < 0) {
        return GOT_ERR;
    } return  0;
}

/*&=&* put a control + data message on a stream *&=&*/
static int put_both(int fd, int clen, int dlen, int pri)
{
    ctl.len = clen;
    dat.len = dlen;
    if(putmsg(fd, &ctl, &dat, pri) < 0) {
        return GOT_ERR;
    } return  0;
}

/*&=&* open file descriptor and attach *&=&*/
static int dl_open(const char *dev, int ppa, int *fd)
{
    dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
    if((*fd = open(dev, O_RDWR)) == -1) {
        return GOT_ERR;
    }
    attach_req->;dl_primitive = DL_ATTACH_REQ;
    attach_req->;dl_ppa = ppa;
    put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
    get_msg(*fd);
    return check_ctrl(DL_OK_ACK);
}

/*&=&* send DL_BIND_REQ *&=&*/
static int dl_bind(int fd, int sap, u_char *addr)
{
    dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
    dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
    bind_req->;dl_primitive = DL_BIND_REQ;
    bind_req->;dl_sap = sap;
    bind_req->;dl_max_conind = 1;
    bind_req->;dl_service_mode = DL_CLDLS;
    bind_req->;dl_conn_mgmt = 0;
    bind_req->;dl_xidtest_flg = 0;
    put_ctrl(fd, sizeof(dl_bind_req_t), 0);
    get_msg(fd);
    if (GOT_ERR == check_ctrl(DL_BIND_ACK)) {
        return GOT_ERR;
    }
    bcopy((u_char *)bind_ack + bind_ack->;dl_addr_offset, addr,
        bind_ack->;dl_addr_length);
    return 0;
}

/**********************************************************************/
/*
* interface:
* function mac_addr_dlpi - get the mac address of the "first" interface
*
* parameter: addr: an array of six bytes, has to be allocated by the
caller
*
* return: 0 if OK, -1 if the address could not be determined
*
*/

long mac_addr_dlpi ( u_char  *addr)
{
    int fd;
    int ppa;
    u_char mac_addr[25];
    int i;

    char **dev;

    for (dev = dlpi_dev; **dev != '\0'; ++dev) {
        for (ppa=0; ppa<10; ++ppa) {
            if (GOT_ERR != dl_open(*dev, ppa, &fd)) {
                if (GOT_ERR != dl_bind(fd, INSAP, mac_addr)) {
                    bcopy( mac_addr, addr, 6);
                    return 0;
                }
            }
            close(fd);
        }
    } return -1;
}


/**********************************************************************/
/*
* Main (only for testing)
*/
#ifdef MAIN
int main( int argc, char **argv)
{
    long stat;
    int i;
    u_char addr[6];

    stat = mac_addr_dlpi( addr);
    if (0 == stat) {
        printf( "MAC address = ");
        for (i=0; i<6; ++i) {
            printf("%2.2x", addr[i]);
        }
        printf( "\n");
    }
    else {
        fprintf( stderr, "can't get MAC address\n");
        exit( 1);
    } return 0;
}
#endif

Link: http://www.asm32.net/article_details.aspx?id=1404


浏览次数 623 发布时间 2006-07-21 02:56:52 从属分类 C/C++ 【评论】【 】【打印】【关闭
 
| www.asm32.net | 2006版 | 资料中心 | linux | asm/asm32 | C/C++ | VC++ | java | Python | 书签 | ASP.Net书签 | 京ICP备09029108号-1