Re: Get Ip Addresses
Re: Get Ip Addresses
- Subject: Re: Get Ip Addresses
- From: Nicko van Someren <email@hidden>
- Date: Mon, 5 Jan 2004 21:04:53 +0000
On 5 Jan 2004, at 20:12, Allen Thomas wrote:
Can someone help me. I am trying to develop a class in Objective C
that would be able to retrieve the network addresses for all the
interfaces currently connected. Much like ifconfig does on the
console. I have looked at a few implementations and could not seem to
be able to use them in my xcode project correctly. Any help would be
great.
The following C code compiles fine for me using Xcode. It's all
standard C and there should be no reason for it not to work in
Objective C. It will probably work on most other Unix platforms too.
You'll find the necessary structures for extracting other information
(broadcast masks etc.) in net/if.h and the necessary ioctl() values in
sys/sockio.h
Cheers,
Nicko
/* Copyright Nicko van Someren 2003. Feel free to edit, reuse and
learn from this. No credit necessary. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netdb.h>
#define CNF_BUF_SIZE 2048
int main(int argc, char **argv)
{
char *s;
int i;
void *buffer;
int sok;
int rc;
struct ifreq rp;
struct sockaddr_in *ap;
u_int32_t ipaddr;
sok = socket(AF_INET, SOCK_DGRAM, 0);
if (sok < 0) {
perror("Getting socket");
exit(1);
}
buffer = malloc(CNF_BUF_SIZE);
if (buffer == NULL) {
perror("Getting conf buffer memory");
exit(1);
}
for(i=1; ; i++) {
s = if_indextoname(i, buffer);
if (s == NULL)
break;
strncpy(rp.ifr_name, s, IFNAMSIZ);
rc = ioctl(sok, SIOCGIFFLAGS, (char *) &rp);
if (rc != 0) {
perror("ioctl on flags");
exit(1);
}
printf("Interface %d: %s, flags: %x\n", i, s, rp.ifr_flags);
if ((rp.ifr_flags & IFF_RUNNING) == 0) {
printf("\tNot running\n");
} else {
if (rp.ifr_flags & IFF_LOOPBACK)
printf("\tLoopback\n");
if (rp.ifr_flags & IFF_POINTOPOINT)
printf("\tPoint to point connection\n");
if ((rp.ifr_flags & IFF_UP) == 0) {
printf("\tDown\n");
} else {
printf("\tUp\n");
}
rc = ioctl(sok, SIOCGIFADDR, (char *) &rp);
if (rc != 0) {
printf("\tNo address assigned\n");
} else {
ap = (struct sockaddr_in *) &rp.ifr_addr;
ipaddr = ap->sin_addr.s_addr;
printf("\tAddress for %s is %d.%d.%d.%d\n", s,
(ipaddr >> 24) & 0xff, (ipaddr >> 16) & 0xff, (ipaddr >> 8) &
0xff, (ipaddr >> 0) & 0xff);
}
}
}
free(buffer);
return 0;
}
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.