/*=========================================================
* Author : Junjie Huang
* Email : acmhjj@gmail.com
* Last modified : 2016-02-19 09:23
* Filename : get_local_ip.c
* Description : 获取本机IP
=========================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
char * getLocalIP(){
int MAXINTERFACES=16;
char * ip = NULL;
int fd, intrface;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
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_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
break;
}
}
}
close(fd);
return ip;
}
}