码迷,mamicode.com
首页 > 其他好文 > 详细

获取IP地址(简单实现)

时间:2014-11-11 20:39:14      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   div   log   bs   

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <sys/socket.h>
  5 #include <sys/select.h>
  6 #include <sys/time.h>
  7 #include <unistd.h>
  8 #include <sys/ioctl.h>
  9 #include <errno.h>
 10 #include <arpa/inet.h>
 11 #include <sys/socket.h>
 12 #include <net/if.h>
 13 #include <net/if_arp.h>
 14 #include <netdb.h>
 15 
 16 #define ETH_NAME  "p1p2" //网卡名字
 17 
 18 int main()
 19 {
 20         int sock;
 21         struct sockaddr_in sin;
 22         struct ifreq ifr;
 23 
 24         sock = socket(AF_INET, SOCK_DGRAM, 0);
 25         if(sock < 0){
 26                 perror("socket");
 27                 return -1;
 28         }
 29 
 30         strcpy(ifr.ifr_name, ETH_NAME);
 31         int ret = ioctl(sock, SIOCGIFADDR, &ifr);
 32         if(ret < 0){
 33                 perror("ioctl");
 34                 return -1;
 35         }
 36 
 37         memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
 38         printf("%s\n", inet_ntoa(sin.sin_addr));
 39         return 0;
 40 }

 

获取IP地址(简单实现)

标签:style   blog   io   color   ar   sp   div   log   bs   

原文地址:http://www.cnblogs.com/luoxiang/p/4090315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!