首页 > 代码库 > Linux编程获取本地IP

Linux编程获取本地IP

 1 #include <stdio.h>      
 2 #include <sys/types.h>
 3 #include <ifaddrs.h>
 4 #include <netinet/in.h> 
 5 #include <string.h> 
 6 #include <stdlib.h>
 7 #include <arpa/inet.h>
 8 
 9 
10 //获取本地IP地址
11 char *getIP()
12 {
13      int sock_get_ip;  
14     char ipaddr[50];  
15   
16     struct   sockaddr_in *sin;  
17     struct   ifreq ifr_ip;     
18   
19     if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1)  
20     {  
21          printf("socket create failse...GetLocalIp!/n");  
22          return "";  
23     }  
24      
25     memset(&ifr_ip, 0, sizeof(ifr_ip));     
26     strncpy(ifr_ip.ifr_name, "eth0", sizeof(ifr_ip.ifr_name) - 1);     
27    
28     if( ioctl( sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0 )     
29     {     
30          return "";     
31     }       
32     sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;     
33     strcpy(ipaddr,inet_ntoa(sin->sin_addr));         
34       
35     printf("local ip:%s /n",ipaddr);      
36     close( sock_get_ip );
37 
38     return ipaddr;
39 }

 

Linux编程获取本地IP