c/c++ function to get machine's own ipaddress

Does anyone know a c/c++ function that can get the local machine’s own
ipaddress? ifconfig enx does this in the shell, i need an equivalent
function. thank you

an example …


#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <errno.h>
#include <net/if.h>
#include <ioctl.h>

int GetInterfaceAddress (const char *if_name, unsigned long int *addr)
{
struct ifreq ifr;
int s;

if (!if_name)
{
*addr = INADDR_ANY;
return 0;
}

if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("%s: %s\n", “socket()”, strerror(errno));
return -1;
}

strcpy(ifr.ifr_name, if_name);

if (ioctl(s, SIOCGIFADDR, &ifr) == -1)
{
printf("%s: %s\n", “ioctl()”, strerror(errno));
return -1;
}

if (close(s) == -1)
return -1;

*addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;

return 0;
}

int main ()
{
unsigned long int addr;

if (GetInterfaceAddress(“lo0”, &addr) == -1)
printf("%s: %s: ‘%s’\n", “GetInterfaceAddress”, “failed”, “lo0”);
else
printf("%s addr %d.%d.%d.%d\n", “lo0”, (int)*(unsigned char )&addr,
(int)
((unsigned char )&addr + 1), (int)((unsigned char )&addr + 2),
(int)
((unsigned char *)&addr + 3));

if (GetInterfaceAddress(“en1”, &addr) == -1)
printf("%s: %s: ‘%s’\n", “GetInterfaceAddress”, “failed”, “en1”);
else
printf("%s addr %d.%d.%d.%d\n", “en1”, (int)*(unsigned char )&addr,
(int)
((unsigned char )&addr + 1), (int)((unsigned char )&addr + 2),
(int)
((unsigned char *)&addr + 3));

if (GetInterfaceAddress(“en2”, &addr) == -1)
printf("%s: %s: ‘%s’\n", “GetInterfaceAddress”, “failed”, “en2”);
else
printf("%s addr %d.%d.%d.%d\n", “en2”, (int)*(unsigned char )&addr,
(int)
((unsigned char )&addr + 1), (int)((unsigned char )&addr + 2),
(int)
((unsigned char *)&addr + 3));

return 0;
}



Ran Zhang napsal(a):

Does anyone know a c/c++ function that can get the local machine’s own
ipaddress? ifconfig enx does this in the shell, i need an equivalent
function. thank you

Hi mezek,

I tried to compile your source code.
However, the compiler return an error as follow:
" undefined reference to `socket’ "

After checking on the socket.h, the function does exist in the header
file.

Is there any setting to the compiler I need to activate so that I can
correct this error?

Rgds

“qnxLearner” <chuayh@cet.st.com-dot-sg.no-spam.invalid> wrote in message
news:d1g86l$inl$1@inn.qnx.com

Hi mezek,

I tried to compile your source code.
However, the compiler return an error as follow:
" undefined reference to `socket’ "

After checking on the socket.h, the function does exist in the header
file.

Is there any setting to the compiler I need to activate so that I can
correct this error?

You need to link with the socket library by specify -lsocket3r.

Rgds