Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1220934
  • 博文数量: 261
  • 博客积分: 4196
  • 博客等级: 上校
  • 技术积分: 3410
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-17 17:05
文章分类

全部博文(261)

文章存档

2018年(1)

2017年(22)

2016年(2)

2015年(8)

2014年(27)

2013年(40)

2012年(161)

分类: LINUX

2012-08-02 10:11:44

from:http://blog.csdn.net/wj4064/article/details/2553158
  1. #include   
  2. #include    
  3. #include    
  4. #include    
  5. #include   
  6. #include    
  7. #include   
  8. #include    
  9. #include    
  10. #include    
  11. #include    
  12. #include    
  13. #include    
  14. #include   
  15.   
  16. int main(int argc, char *argv[])    
  17. {    
  18.   
  19.     char ipbuf[16];    
  20.     getlocaip(ipbuf);    
  21.   
  22.     printf("loca ip = %s/n", ipbuf);     
  23.     exit(0);      
  24.   
  25. }  
  26.     
  27. int getlocaip(char *ip)    
  28. {    
  29.     int sockfd;     
  30.     
  31.     if(-1 == (sockfd = socket(PF_INET, SOCK_STREAM, 0)))    
  32.     {    
  33.         perror( "socket" );    
  34.         return -1;    
  35.     }  
  36.         
  37.    struct ifreq req;    
  38.     struct sockaddr_in *host;    
  39.     bzero(&req, sizeof(struct ifreq));    
  40.     strcpy(req.ifr_name, "eth0");    
  41.     ioctl(sockfd, SIOCGIFADDR, &req);    //设置IP
  42.     host = (struct sockaddr_in*)&req.ifr_addr;    
  43.     strcpy(ip, inet_ntoa(host->sin_addr));    
  44.     close(sockfd);        
  45.     return 1;    
  46. }  

SIOCGSIZIFCONF 获得获取 SIOCGIFCONF 返回的所有接口的配置信息所需的内存。
		
ioctl(fd, SIOCGSIZIFCONF, (caddr_t)&ifconfsize);

int ifconfsize;

SIOCGIFADDR

SIOCSIFADDR
SIOCGIFADDR 获取接口地址,而 SIOCSIFADDR 设置接口地址。ifr.ifr_addr 字段返回地址。
ioctl(fd, SIOCGIFADDR, (caddr_t)&ifr, sizeof(struct ifreq));

ioctl(fd, SIOCSIFADDR, (caddr_t)&ifr, sizeof(struct ifreq));

struct ifreq ifr;

SIOCGIFCONF 返回系统中配置的所有接口的配置信息。
ioctl(fd, SIOCGIFCONF, (caddr_t)&ifc);

struct ifconf ifconf;
阅读(2211) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~