程序功能:
本程序主要获取本地的IP地址
思路分析:
#include <stdio.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#define BUFSIZE 128
int main(void)
{
int sock_fd;
struct ifconf conf;
struct ifreq *ifr;
struct sockaddr_in *sin;
char buff[BUFSIZE];
int num, i;
if( (sock_fd = socket(PF_INET, SOCK_DGRAM, 0))<0)
{
perror("socket");
return -1;
}
conf.ifc_len = BUFSIZE;
conf.ifc_buf = buff;
ioctl(sock_fd, SIOCGIFCONF, &conf); //获取所有接口的清单
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;
for(i = 0; i < num; i++){
sin = (struct sockaddr_in *)(&ifr->ifr_addr);
ioctl(sock_fd, SIOCGIFFLAGS, ifr); //获取接口标志
if(((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP)){
printf("%s (%s)\n", ifr->ifr_name, inet_ntoa(sin->sin_addr));
}
ifr++;
}
}
运行结果:
注释:
1》//PF_INET<=>AF_INET AF = Address Family PF = Protocol Family; //SOCK_DGRAM:UDP
2》//SIOCGIFCONF 参见:http://www.cppblog.com/wgcno7/archive/2010/04/21/115963.html