//接下来一个一个的获取IP地址
ifreq = (struct ifreq*)buf;
for(i=(ifconf.ifc_len/sizeof(struct ifreq)); i>0; i–)
{
ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr);
if(strcmp(ip,”127.0.0.1″)==0)  //排除127.0.0.1,继续下一个
{
ifreq++;
continue;
}
strcpy(outip,ip);
return 0;
}
return -1;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>
long getlocalhostip ()
{
int MAXINTERFACES = 16;
long ip;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
ip = -1;
if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) {
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-- > 0) {
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
ip = inet_addr (inet_ntoa (((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr));
break;
}
}
}
close (fd);
}
return ip;
}
union ipu
{
long ip;
unsigned char ipchar[4];
};
int main (int argc, char **argv)
{
union ipu localip;
localip.ip = getlocalhostip ();
printf ("local ip:%x :%u.%u.%u.%u ", localip.ip, localip.ipchar[0], localip.ipchar[1], localip.ipchar[2], localip.ipchar[3]);
return 0;
}