f



sample code to get MAC and IP address no Mac OS X

This sample shows how to get the MAC and IP address of all network
interfaces without having to use IOKit. I don't think this is portable
to Linux due to some BSD specific things. I got some of the code from
here:
http://koders.com/c/fidE434A12145571115B48BF3CF7A450F6AF93FC109.aspx?s=SIOCGIFCONF

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/errno.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/ethernet.h>
#include <sys/types.h>
#include <sys/sysctl.h>


using namespace std;

int main(int argc, char *argv[])
{
   char * buf = NULL;
   struct ifconf ifc;
   int socketID = 0;

   // we need a socket to call ioctl on
   socketID = socket(AF_INET, SOCK_STREAM, 0);
   if (socketID == -1)
   {
      printf("error calling socket\n");
      return -1;
   }

   // keep calling ioctl until we provide it a big enough buffer
   {
      int numreqs = 100;
      buf = (char*) malloc(sizeof(struct ifreq) * numreqs);

      for (;;)
      {
         ifc.ifc_len = sizeof(struct ifreq) * numreqs;
         ifc.ifc_buf = buf;

         if (ioctl(socketID, SIOCGIFCONF, &ifc) < 0)
         {
            printf("error calling ioctl: %s\n", strerror(errno));
            return -1;
         }

         if (ifc.ifc_len / sizeof(struct ifreq) == numreqs)
         {
            // there's more to read
            numreqs *= 2;
            buf = (char*) realloc(buf, sizeof(struct ifreq) * numreqs);
         }
         else
         {
            // we're read as much as we can
            break;
         }
      }
   }

   // iterate through each interface
   for (int n = 0; n < ifc.ifc_len; )
   {
      struct ifreq * ifr = (struct ifreq*) (((char*) ifc.ifc_req ) +
n);

      n += sizeof(ifr->ifr_name) +
         (ifr->ifr_addr.sa_len > sizeof(struct sockaddr)
         ? ifr->ifr_addr.sa_len : sizeof(struct sockaddr));

      if (ifr->ifr_addr.sa_family != AF_INET)
         continue;

      // make sure the interface is UP
      {
         if (ioctl(socketID, SIOCGIFFLAGS, ifr) < 0)
         {
            printf("error calling ioctl: %s\n", strerror(errno));
            continue;
         }

         if (!(ifr->ifr_flags & IFF_UP))
            continue;
      }

      // the IP address
      {
         struct in_addr *ia;
         ia = (struct in_addr *) ((ifr->ifr_ifru.ifru_addr.sa_data)+2);
         printf("%6s %-15s\n", ifr->ifr_name, inet_ntoa(*ia));
      }

      // mac address
      {
         int mib[6], len;

         mib[0] = CTL_NET;
         mib[1] = AF_ROUTE;
         mib[2] = 0;
         mib[3] = AF_LINK;
         mib[4] = NET_RT_IFLIST;
         mib[5] = if_nametoindex(ifr->ifr_name);

         if (mib[5] == 0)
         {
            printf("error calling if_nametoindex\n");
            continue;
         }

         if (sysctl(mib, 6, NULL, (size_t*)&len, NULL, 0) < 0)
         {
            printf("sysctl 1 error\n");
            continue;
         }

         char * macbuf = (char*) malloc(len);
         if (sysctl(mib, 6, macbuf, (size_t*)&len, NULL, 0) < 0)
         {
            printf("sysctl 2 error");
            continue;
         }

         struct if_msghdr * ifm = (struct if_msghdr *)macbuf;
         struct sockaddr_dl * sdl = (struct sockaddr_dl *)(ifm + 1);
         unsigned char * ptr = (unsigned char *)LLADDR(sdl);
         printf("MacAddress: %02x:%02x:%02x:%02x:%02x:%02x\n", *ptr,
*(ptr+1), *(ptr+2),
            *(ptr+3), *(ptr+4), *(ptr+5));

         free(macbuf);
      }

   }
   
   // clean up
   free(buf);
   close(socketID);
   
   return 0;
}

0
Sailesh
8/25/2005 7:01:37 AM
comp.sys.mac.programmer.help 4653 articles. 2 followers. Post Follow

2 Replies
1472 Views

Similar Articles

[PageSpeed] 44

>       int numreqs = 100;
>       buf = (char*) malloc(sizeof(struct ifreq) * numreqs);

oops, that should be numreqs = 16, or some low number. I was doing 100
just for testing.

0
Sailesh
8/25/2005 8:31:52 AM
On BSD systems that have it, the getifaddrs(3) function provides a
much simpler interface to getting this information, and I would
recommend that you use it instead of ioctl().

In your code you skip interfaces that are not AF_INET, but in doing so
you miss AF_LINK interfaces, from which you can obtain the MAC address
directly instead of calling sysctl().
0
rhsu
9/5/2005 4:04:27 AM
Reply:

Similar Artilces:

change mac address get mac address spoofing mac address find computer by mac address
Mac Address Spoofing Report Victor J. Canny D. Abstract: Mac address can uniquely identifies each node of a network, ISPs and network administrators use mac address to manage their pc users. PC users may want to spoof mac address so that he need not to contact with ISP for a new network interface card (NIC); PC users may want to hide his mac address so that totally hide his information on the internet. Introduction Mac address, short for Media Access Control address, is a hardware address that uniquely identifies each node of a network. It means, in a local area network (LAN) or oth...

[ANN] Graphviz for Mac OS X 1.12 (v8) [ANN] Graphviz for Mac OS X 1.12 (v8) [ANN] Graphviz for Mac OS X 1.12 (v8)
Hi all, It's been a busy week or two at Pixelglow Software. Here's a brand new version of Graphviz, all spit and polish now. You'll enjoy the integrated color and font panel support, hand cursor panning and remembered settings. And everyone's most asked for -- a single click on the Edit tool will now bring up the DOT code for you to edit, and of course when you save it the graph automatically re-renders. http://www.pixelglow.com/graphviz/download/ Here's the lowdown: Added edit, render and stop toolbar items [PCh]. Added integrated font and color fields and panels. Adde...

[ANN] Graphviz for Mac OS X 1.12 (v10) [ANN] Graphviz for Mac OS X 1.12 (v8) [ANN] Graphviz for Mac OS X 1.12 (v8)
Hi all, Yet another Graphviz version. The old application icon had been voted off the island, and brand new application and document icons flown in for the task. Comprehensive help features in this version too. http://www.pixelglow.com/graphviz/ What's new: ------------ Added new application and document icons. Added comprehensive help. Fixed changes not affecting graph size displaying incorrectly [BTr]. Fixed export then close crashing the export of an open window. Improved shadowed frame for graph [NRi]. Improved status display [NRi]. Changed sources to pure BSD license. Cheers, Gl...

[ANN] Graphviz for Mac OS X 1.12 (v12) [ANN] Graphviz for Mac OS X 1.12 (v8) [ANN] Graphviz for Mac OS X 1.12 (v8)
Dear All: Them pesky bugs. A few more squashed courtesy of the sleepy pixel. http://www.pixelglow.com/graphviz/ What's new in v11 ------------ Fixed some comprehensive help [NRi]. Fixed scale option placeholder [NRi]. Improved application and document icons. Example files now double-click to open in application. What's new in v12 ------------ Added layout option tooltips [NRi]. Fixed layout popup button changing wrong graph [MKe]. Clicking on warning icon now opens Activity window [NRi, AM]. Revert menu item now disabled. Cheers, Glen Low --- pixelglow software | simply brillian...

[ANN] Graphviz for Mac OS X 1.13 (v13) [ANN] Graphviz for Mac OS X 1.12 (v8) [ANN] Graphviz for Mac OS X 1.12 (v8)
Dear All, I've just released the newest version of Mac Graphviz, featuring shapefile support and enhanced zoom. http://www.pixelglow.com/graphviz/ Shapefiles supported include PDF, EPS, PS, JPEG, PNG and all Quicktime formats. Either specify an absolute or relative (to working directory) file path, or a URL using the shapefile attribute. Developers can now also use the graphviz.framework directly with #include headers in C e.g. using Xcode "Add Frameworks..."; documentation is available from the main Graphviz site -- http://www.research.att.com/sw/tools/graphviz/libguide.pdf...

Your Mac won't start up in Mac OS X (Mac OS X 10.3.9 or earlier)
Your Mac won't start up in Mac OS X (Mac OS X 10.3.9 or earlier) Nothing can be more frustrating than turning on your Mac only to find that it won't start up. Instead of seeing the Finder, you see a blue or gray screen, an icon of a broken folder, a kernel panic, a flashing question mark, or a computer that just sits there. What can you do? Don't worry. It could be a simple issue that you can fix yourself. Note: This article applies to Mac OS X 10.3.9 or earlier. Tip: If your computer won't start at all, skip to "You see a blank, gray screen" below. The first step ...

PDF to EPS workarounds for Mac OS X Attention TeXy, TeXy peoples: PDF to EPS workarounds for Mac OS X Attention TeXy, TeXy peoples: PDF to EPS workarounds for Mac OS X Attention TeXy, TeXy
Attention TeXy, TeXy peoples: (excuse the mispronunciation; punny licence) It seems that Mac OS X has partially documented issues (http://altair.ific.uv.es/~JaxoDraw/Bugparade/bugparade.htm, http://developer.apple.com/java/faq/issues.html#anchor6) with the generation of EPS, and I'm trying to find a workaround. The Preview application cannot export to eps, but it can read it (converting it to PDF). If I use Adobe Acrobat to read the PDF generated by Preview, the EPS it generates sometimes (inconsistently) causes dvips to make an unreadable file. What I'm trying to do is the followi...

Help! iSync mac to mac
Am I right in saying that with iSync, if you want to sync 2 macs together (address book, iCal etc.) the only way to do this is via a ..Mac account, even if those computers are sitting not 5 feet from each other, both Airport equipped? If this is the case, I've never heard anything so ridiculous. Is this just part of another apple scam to get more money out of us? Does anyone know if this is indeed the case, and can you recommend any other sync software out there? I'm setting up an iMac, eMac and powerbook g4 for a friend's office, all running OSX Panther, and you'd think basi...

Mac OS 9.x included in Mac OS X?
Hi, I read that Mac OS X has a so-called classic mode which emulates Mac OS 9.x so that older applications can still be run. Provided one is not an upgrader from Mac OS 9.x, does Mac OS X include Mac OS 9.x required for the classic mode or does it have to be bought separately? Peter >Provided one is not an upgrader from Mac OS 9.x, does Mac OS X include >Mac OS 9.x required for the classic mode or does it have to be bought >separately? If you buy the installer for OS X it *does not* include OS 9. You generally use the copy of OS 9 that came with your computer in order to install C...

Mac OS X & Mac OS X Server
Hi, I'm currently using a 9i developer release on Mac OS X (10.3) which has proved very stable so far. My understanding of the various Oracle press releases is that 10G will be released for Mac OS X, are there any beta testers out there wiling to comment on availabilitu/quality/performance issues for 10G on Mac OS X? Another question is whether tools such as the OEM will be available in 10G for Mac OS X, does anybody know? Yours in anticipation! Steve Steve <steve@nospam.com> wrote in message news:<2004013008345616807%steve@nospamcom>... > releases is that 10G wil...

You cannot install Mac OS X on this volume. Mac OS X cannot start up from this volume.
Hi Group, Decided to reinstall OSX today on my MAC Book. _ Boy was this a mistake_ I booted off the DVD and changed the partition setup to two instead of one using the disk utility program. Selected MAC OSX Extended Journaled for both paritions. Now in the installer when I come to select the drive to install on I get the message "You cannot install Mac OS X on this volume. Mac OS X cannot start up from this volume." There is a red explaination mark on the drive. I have reboot, reformatted the drive back one parition using the disk util program and I still have the same proble...

To Mac or not to Mac?
What ho, pre-pressers! Long time no post, or view, come to that. No doubt some of you will remember me as I see that many of same crowd are **STILL** here after all these years. Grettings to Aandi, Ted, Lee, Allen...well, to you all, not forgetting Mr Shagnasty, who I am gratified can still find something to say after all this time. Right, greetings over, down to brass tacks. My early retirement plan has sadly fallen through and I find myself back at the coal face possessed of some pretty antideluvian equipment with which to earn a crust for the Tree family. So I'm looking for **SE...

No Mac Help in Mac Help?
When I go to Mac Help in Finder (latest version of OSX Tiger) I get nothing. The window pops up but it's blank. Click on the little house and the initial screen fills in but nothing beyond that. I had a simiar problem with Safari help some time back and someone suggested I remove a folder from Library/Caches, (com.apple.helpui or something similar) and that did the trick for Safari's help. I honestly don't recall if I've ever had the Mac Help or I've just never used it since this machine. The problem happens on or offline so I'm not sure where the Mac Help file re...

When is a Mac not a Mac?
This was posted in a forum recently and I thought it brought up some very interesting points relating to the Eula. For reference: http://forum.insanelymac.com/index.php?showtopic=105546 ------ This question is related to licensing OS X on a machine. The EULA says it has to be an Apple computer, before the Apple License will apply, which means Apple will only support OS X on Apple machines. So, I'm wondering, when is a machine considered an Apple Mac, for the purposes of Licensing and recieving support? Say I buy a Mac from Apple. Then the hard drive fails, and I replace that with an ...

Mac to mac
I just remembered these groups and wondered if someone here could tell me whether what I'd like to do is possible. (NO ONE around here knows anything about Macs) I have a G4 that was the top of the line in 1998. It will die one of these days. It's currently running OS 9.2.2. Someone else(who now lives far away) installed the internal modem, SCSI for my scanner, and my floppy drive (so I didn't have to go through hundreds of them for the bits and pieces I might someday want again). I still have the floppies and a number of Zips, all of which this computer can read. Install...

Mac OS X Kerberos Extras updated for Mac OS X 10.3
-----BEGIN PGP SIGNED MESSAGE----- Just a reminder to coincide with today's release of Mac OS X 10.3 ("Panther"), the MIT Kerberos team has released an updated version of the Mac OS X Kerberos Extras that work with both Mac OS X 10.2 (Jaguar) and Mac OS X 10.3 (Panther). The Mac OS X Kerberos Extras allow CFM-based applications, such as Eudora and Fetch, to work with OS X's built-in Kerberos. Older releases of the OS X Kerberos Extras will not work with Mac OS X 10.3. You must have the latest release (which was released back in June) for it to work with Panther. However...

Mac os 9 Vs. Mac os X
I am porting some windows software to mac os 9. My client has only mac os 9. I would like to use the URLAccessLib for my development. I find no documentation of it on Apple websites as if mac os 9 has fallen off the earth for them. The apple site says One can develop on mac os x and it is backward compatible. What does this mean ? When I install my code on mac os 9 will I need all the mac os x libraries ? can someone throw somelight ? Thanks >The apple site says One can develop on mac os x and it is backward >compatible. What does this mean ? When I install my code on mac os 9 >wi...

Mac os 9 Vs. Mac os X
I am porting some windows software to mac os 9. My client has only mac os 9. I would like to use the URLAccessLib for my development. I find no documentation of it on Apple websites as if mac os 9 has fallen off the earth for them. The apple site says One can develop on mac os x and it is backward compatible. What does this mean ? When I install my code on mac os 9 will I need all the mac os x libraries ? can someone throw somelight ? Thanks On 21 Nov 2003, dharmesh wrote: > I am porting some windows software to mac os 9. My client has only mac > os 9. I would like to...

Mac OS X fonts in Mac OS 9
Dear all, Is it possible to use MacOS X fonts in the classic environment? What's the procedure if it is ... Cheers! In article <3bef037b.0411010152.7625d932@posting.google.com>, davidol@hushmail.com (David) wrote: > Is it possible to use MacOS X fonts in the classic environment? > What's the procedure if it is ... No problem: a) TrueType fonts (.ttf - the vast majority) can simply be *moved* to the fonts folder in your Classic system folder. b) OpenType fonts (.otf) can be placed there as well but require Adobe Type Manager Light to work: <http://www.adobe....

Getting files from a IIGS to a Mac OS X Mac (G5)... how can you do it?
Hi all. I am the owner of a IIGS and in macdom, a G5. Back when I had a powermac 7500/100, both the Mac and IIGS were able to read and write to the same physical floppy disks, so getting games and files outta my IIGS and over to my mac was easy. And getting games off the internet and over to my IIGS was also easy (and rather miraculous-seeming). But then Macs stopped supporting floppies. Years passed, and as far as I can see, the Mac and the IIGS are almost strangers to each other now. I've read about null modem cables, but most posts on this topic archived on the net seem to be pretty l...

Are Mac OS X 10.5.8's iLife programs safe to use in Mac OS X 10.7.x and 10.8.x?
Hi. Someone told me that Mac OS X 10.7.x and 10.8.x do not come with iLife like the older Mac OS X versions (e.g., 10.5.x). I did not know this! Since my client uses iPhoto that came preinstalled on his old 2008 MacBook Pro's Mac OS X 10.5.x (10.5.8 right now), can he use the old one from 10.5.8? Or will he need a third party replacement (needs to import/copy the old image files) or buy a new iPhoto version for his photo(graph)s? I recalled he did not like iPhoto and wonder if the new one is any better. Thank you in advance. :) -- Quote of the Week: "Every ruler...

FS: Mac OS X v10.2 and Mac OS X v10.3 (Panther)
clearing up my storeroom. we have moved to tiger. OS10.2 are the original two cds from apple OS10.3 (Panther) are the original three cds from apple. prices: best offer -- getting out of bed in the morning is an act of false confidence - jules feifer to email me, delete syzygy. from my return address ...

Mac OS X 1.0 x86 and Mac OS X 10.4 x86
I wonder of OS X on Intel runs binaries made for Mac OS X Server 1.0 or earlier x86 versions of NEXTSTEP... There should be some interesting error messages to find. I'll try it out with OmniWeb 3 one day... -- Andrew J. Brehm Marx Brothers Fan PowerPC/Macintosh User Supporter of Chicken Sandwiches In article <1gxrpng.qcld42zk38uoN%ajbrehm@gmail.com>, ajbrehm@gmail.com (Andrew J. Brehm) wrote: > I wonder of OS X on Intel runs binaries made for Mac OS X Server 1.0 or > earlier x86 versions of NEXTSTEP... > > There should be some interesting error messages to find. &...

Looking for source code (Get Mac address from IP address)
I think this is like an arp request... What I'm looking for is unix source code of a method to get the mac address of a computer given its IP / host name. C/C++. Or a good tutorial... TIA. On Tue, 20 Jan 2009 10:07:44 -0800, SpreadTooThin wrote: > I think this is like an arp request... What I'm looking for is unix > source code of a method to get the mac address of a computer given its > IP / host name. C/C++. Or a good tutorial... > TIA. Something like (untested): #/bin/sh ping -n 1 <ip> >/dev/null 2>&1 arp -a | fgrep <ip> M...

Web resources about - sample code to get MAC and IP address no Mac OS X - comp.sys.mac.programmer.help

IPv4 address exhaustion - Wikipedia, the free encyclopedia
IPv4 address exhaustion is the depletion of the pool of unallocated Internet Protocol Version 4 (IPv4) addresses. The IP address space is managed ...

Scott Morrison to focus on tax cuts in Press Club address, MPs warn against negative gearing
... on cutting spending, as the Coalition backbench agitates against any changes to negative gearing. Mr Morrison will today make his first address ...

Irish planning body asks Apple to address five concerns before it decides on proposed data center
... those objections. Business Insider reports that An Bord Pleanála has now written to Apple’s consulting engineers, asking them to address five ...

Gmailify: The best of Gmail, without an @gmail address
... features, like spam protection and inbox organization , on these accounts—but don’t want to go through the hassle of changing your email address. ...

You Can Now Access Gmail Features Without An @Gmail Address
It’s tough to get people to switch from one email service to another — getting a new email address might be even more annoying than having to ...

Sanders Campaign Staffers Admit Using False Address To Vote
Sanders Campaign Staffers Admit Using False Address To Vote

Obama pitches 'politics of hope,' voting rights in weekly address
... Your president wants to have a word with you about how you do politics. He’s not happy, and he made that clear in this morning’s weekly address: ...

'Gmailify' gives you Gmail service without the Gmail address
Last March, Google began allowing its users to link their Gmail account with their Yahoo! and Outlook accounts so that all of their emails could ...

Chipotle Used Video To Address Its Entire Workforce. Could You?
What happens when your business is food and it sickens 500 people? If you're Chipotle you close your stores and produce an all-hands video address ...

Watch Neil deGrasse Tyson’s Reply to the Gettysburg Address
Neil deGrasse Tyson was asked to provide a response to Abraham Lincoln’s Gettysburg Address. The result, animated by by Loaded Pictures , is ...

Resources last updated: 2/19/2016 5:58:15 PM