Created
February 19, 2016 01:25
-
-
Save osvimer/48207c01aae112efc6d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*========================================================= | |
* Author : Junjie Huang | |
* Email : [email protected] | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment