#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ifaddrs.h>
int main (int argc, const char * argv[]) {
// insert code here...
int result;
struct ifaddrs *ifbase, *ifiterator;
result = getifaddrs(&ifbase);
ifiterator = ifbase;
while (!result && (ifiterator != NULL))
{
if (ifiterator->ifa_addr->sa_family == AF_INET)
{
struct sockaddr *saddr, *netmask, *daddr;
saddr = ifiterator->ifa_addr;
netmask = ifiterator->ifa_netmask;
daddr = ifiterator->ifa_dstaddr;
// we've found an entry for the IP address
struct sockaddr_in *iaddr;
char addrstr[64];
iaddr = (struct sockaddr_in *)saddr;
inet_ntop(saddr->sa_family, &iaddr->sin_addr, addrstr, sizeof(addrstr));
fprintf(stderr, "ipv4 enet interface name %s, source IP addr %s ", ifiterator->ifa_name, addrstr);
iaddr = (struct sockaddr_in *)netmask;
if (iaddr)
{
inet_ntop(saddr->sa_family, &iaddr->sin_addr, addrstr, sizeof(addrstr));
fprintf(stderr, "netmask IP addr %s ", addrstr);
}
iaddr = (struct sockaddr_in *)daddr;
if (iaddr)
{
inet_ntop(saddr->sa_family, &iaddr->sin_addr, addrstr, sizeof(addrstr));
fprintf(stderr, "dest/broadcast IP addr %s.\n\n", addrstr);
}
}
else if (ifiterator->ifa_addr->sa_family == AF_INET6)
{
// we've found an entry for the IP address
struct sockaddr_in6 *iaddr6 = (struct sockaddr_in6 *)ifiterator->ifa_addr;
char addrstr[256];
inet_ntop(ifiterator->ifa_addr->sa_family, iaddr6, addrstr, sizeof(addrstr));
fprintf(stderr, "ipv6 enet interface name %s, source IP addr %s \n\n", ifiterator->ifa_name, addrstr);
}
ifiterator = ifiterator->ifa_next;
}
return 0;
}
On Feb 28, 2008, at 4:54 PM, Hamish Allan wrote:
Hi,
Is there a way to programmatically discover a machine's subnet mask?
I can see how this might be done using AppleScript to query System
Preferences but I'm hoping for something a bit more portable than that
(yes I know this is a Mac list but I think some members have wider
expertise. Also, the only 3 results for mailing lists returned from
googling "network programming mailing list" are for this one!)
Preferably in cross-platform Python, but beggars can't be choosers :)
Hamish
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/macnetworkprog/email@hidden
This email sent to email@hidden