Linux 下获取本机IP

时间:2022-06-20 08:07:03

http://blog.csdn.net/K346K346/article/details/48231933

int main ()
{
/*
struct ifaddrs *ifap, *ifa;
struct sockaddr_in *sa;
char *addr; getifaddrs (&ifap);
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family==AF_INET) {
sa = (struct sockaddr_in *) ifa->ifa_addr;
addr = inet_ntoa(sa->sin_addr);
printf("Interface: %s\tAddress: %s, %x \n", ifa->ifa_name, addr,sa->sin_addr);
}
} freeifaddrs(ifap); */

/*
//设置为本机IP,如果获取地址失败则使用hostname,这种获取方式依赖/etc/hosts,获取不准。
// 获取本机地址,只取一个
hostent* pHost = gethostbyname(host_name);
if ( pHost != 0 )
{
for ( int i = 0; pHost != 0 && pHost->h_addr_list[i] != 0; i++ )
{
if((unsigned int)((unsigned char*)pHost->h_addr_list[i])[0] == 127)
continue;
char ip_str[16] = {0};
sprintf( ip_str, "%x%x%x%x",(unsigned int)((unsigned char*)pHost->h_addr_list[i])[0],
(unsigned int)((unsigned char*)pHost->h_addr_list[i])[1],
(unsigned int)((unsigned char*)pHost->h_addr_list[i])[2],
(unsigned int)((unsigned char*)pHost->h_addr_list[i])[3]);
host_id_ = ip_str;


break;
}
}
*/

struct ifaddrs *ifap, *ifa;
struct sockaddr_in *sa;

getifaddrs (&ifap);
for (ifa = ifap; ifa; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET)
{
if(strncmp(ifa->ifa_name, "lo", 2) == 0)
continue;

sa = (struct sockaddr_in *) ifa->ifa_addr;
char ip_str[16] = {0};
sprintf(ip_str,"%08x", sa->sin_addr);
printf("---%s \n",ip_str);
printf("%d,%d,%d,%d \n",sizeof(sa->sin_addr),sizeof(int),sizeof(unsigned long), sizeof(unsigned long long));
}
}
freeifaddrs(ifap);

return 0;
}