Error Given by Compiler

Hi,

I tried to compile the following source code on QNX 6.3.0.
I am trying to use the C function to create socket.

/******************* Start Of Code ***************************/
#include <stdio.h>

#include <sys/types.h>

#include <sys/socket.h>
#include <netinet/in.h>

#include <errno.h>
#include <net/if.h>
#include <ioctl.h>

int GetInterfaceAddress (const char *, unsigned long int *);

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;
}

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;
}

/********************* End of Code **************************** /

The compiler produce an error as follow:

  • In function GetInterfaceAddress': undefined reference to socket’

I checked the header file, socket.h. The function socket() is included in the header file.

what could have gone wrong?
Is there any settting I have to make to the setting of compiler so that the source code above can be compiled successfully?

Can anybody help me on this?

Rgds

The error doesn’t come from the compiler but from the linker. You need to link with the socket library by specify -lsocket