Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Localhost IP



On Thursday, March 28, 2002, at 10:56 AM, Julien Guimont wrote:

Hi there!

I have a little question for you all. I try to get the local IP of my
system. I came to this solution:
...
Works great but only for 127.0.0.1, not my other 192.168.0.10 IP.

Is there a way to bypass that? Find the IP and go to sleep?;)

Julien Guimont,
email@hidden
http://www.juggysoft.com

Cheers Julien

If you have a connected socket, you can use getsockname() to return the IP address of the local end of your connection.

Example code follows

------
typedef union {
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
} sockaddr_union;


int TCPLocalIP(int sockfd, struct in_addr *ip)
{
sockaddr_union sau;
int len;

len = sizeof(sockaddr_union);
if(getsockname(sockfd, (SA *) &sau.sa, &len) < 0)
return (-1);

memcpy(ip, &sau.sin.sin_addr, sizeof(ip));
return (0);
}
------

If you do not have an connected socket, you can enumerate through the interfaces; get the list using the following sysctl MIB.

mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0;
mib[3] = 0;
mib[4] = NET_RT_IFLIST;
mib[5] = 0;

See sysctl(3) for more information.

getifaddrs() implements this, but I did not see it in a quick check of Darwin.
Refer to http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/net/getifaddrs.c
You can either use their implementation, or learn from their example.

Good luck,
Landon Fuller
email@hidden
http://oscar.garbage.dk
_______________________________________________
darwin-development mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/darwin-development
Do not post admin requests to the list. They will be ignored.



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.