linux下获取本机IP
转载:http://blog.chinaunix.net/uid-20593763-id-1620213.html
源代码级Unix/Linux 通用网卡IP地址获取方法
gethostbyname通过域名解析获取对应计算机的网络地址,ioctl是一系列的网络函数获得本机的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>
int main(void)
{
int s;
struct ifconf conf;
struct ifreq *ifr;
char buff[BUFSIZ];
int num;
int i;
s = socket(PF_INET, SOCK_DGRAM, 0);
conf.ifc_len = BUFSIZ;
conf.ifc_buf = buff;
ioctl(s, SIOCGIFCONF, &conf);
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;
for(i=0;i < num;i++)
{
struct sockaddr_in *sin = (struct sockaddr_in *)(&ifr->ifr_addr);
ioctl(s, 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++;
}
}
输出:
主要通过这两个函数:gethostname()和gethostbyname()
int gethostname(char *name, size_t namelen);
DESCRIPTION
The gethostname() function shall return the standard host name for the current machine. The namelen argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that if namelen
is an insufficient length to hold the host name, then the returned name
shall be truncated and it is unspecified whether the returned name is
null-terminated.Host names are limited to {HOST_NAME_MAX} bytes.
struct hostent *gethostbyname(const char *name);
这个函数的传入值是域名或者主机名,例如"www.google.com","wpc"等等。
传出值,是一个hostent的结构(如下)。如果函数调用失败,将返回NULL。
struct hostent {
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
};
解释一下这个结构:
其中,
char *h_name 表示的是主机的规范名。例如www.google.com的规范名其实是www.l.google.com。
char **h_aliases 表示的是主机的别名。www.google.com就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
int h_addrtype 表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)
int h_length 表示的是主机ip地址的长度
int **h_addr_lisst 表示的是主机的ip地址,注意,这个是以网络字节序存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。
这个函数,其实就是返回指向dst的一个指针。如果函数调用错误,返回值是NULL。
下面是例程,有详细的注释。
#include <stdio.h>
#include <arpa/inet.h> //for inet_ntop()
#include <unistd.h> //for gethostname()
#include <netdb.h> //for gethostbyname()
#include <sys/socket.h>
int main(int argc, char **argv)
{
char **pptr;
struct hostent *hptr;
char hostname[32];
char str[32];
if(gethostname(hostname,sizeof(hostname)) )
{
printf("gethostname calling error\n");
return 1;
}
/* 调用gethostbyname()。调用结果都存在hptr中 */
if( (hptr = gethostbyname(hostname) ) == NULL )
{
printf("gethostbyname error for host:%s\n", hostname);
return 0; /* 如果调用gethostbyname发生错误,返回1 */
}
/* 将主机的规范名打出来 */
printf("official hostname:%s\n",hptr->h_name);
/* 主机可能有多个别名,将所有别名分别打出来 */
for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
printf(" alias:%s\n",*pptr);
/* 根据地址类型,将地址打出来 */
switch(hptr->h_addrtype)
{
case AF_INET:
case AF_INET6:
pptr=hptr->h_addr_list;
/* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */
for(;*pptr!=NULL;pptr++)
printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
break;
default:
printf("unknown address type\n");
break;
}
return 0;
}
运行输出结果:
official hostname:localhost.localdomain
alias:localhost
address:127.0.0.1
(给出的这个ip好像没什么意义,在另外一台机器上运行,给出ip是:192.168.0.3,而ifconfig给出的ip是192.168.2.100,这是怎么回事?虽然电脑都有双网卡)
linux下获取本机IP的更多相关文章
- Linux下获取本机IP地址的代码
Linux下获取本机IP地址的代码,返回值即为互联网标准点分格式的字符串. #define ETH_NAME "eth0" //获得本机IP地址 char* GetLocalAdd ...
- Linux 下获取本机IP
http://blog.csdn.net/K346K346/article/details/48231933 int main () { /* struct ifaddrs *ifap, *ifa; ...
- Windows下获取本机IP地址方法介绍
Windows下获取本机IP地址方法介绍 if((hostinfo = gethostbyname(name)) != NULL) { #if 1 ; printf("IP COUNT: % ...
- Linux下获得本机IP(非127.0.0.1)
在Linux下用InetAddress.getLocalHost()方法获取本机IP地址,得到的结果总是:127.0.1.1.原来这个是etc/hosts文件中的配置,并非网卡的IP地址. 可用代码如 ...
- QT5下获取本机IP地址、计算机名、网络连接名、MAC地址、子网掩码、广播地址
获取主机名称 /* * 名称:get_localmachine_name * 功能:获取本机机器名称 * 参数:no * 返回:QString */ QString CafesClient::get_ ...
- Linux下获取和设置IP
在Linux下获取关于IP和网关的操作:重点是对struct ifreq 的操作. 那么进入目录/usr/include/net/if.h下看查找struct ifreq结构体. /* Interfa ...
- rust下获取本机IP
又拾起了rust语言, 想写一点东西玩一玩, 但是发现连一个获取本机IP地址的库都没有, 还得挽起袖子自己撸. https://crates.io/crates/local_ipaddress 没有用 ...
- python未知网卡名情况下获取本机IP
import socket def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even ...
- windows和linux下的本机IP的获取(亲测有效)
package com.handsight.platform.fras.util; import org.apache.log4j.Logger; import javax.servlet.http. ...
随机推荐
- [Tools] Eclipse更改类注释自动生成模板
[背景] 使用之中发现一些eclipse使用的小技巧,记录下来供以后查阅 由于机器是老婆的,创建新类的时候或者生成注释的时候全都是她的名字,避免弄混,需要设置一下: 设置创建新类时自动生成类或方法 ...
- 静态内容生成器——Wyam
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:今天继续静态网站的话题,介绍我选用的一个使用.NET开发的静态内容生成器--Wyam. ...
- Debian 的 preinst, postinst, prerm, 和 postrm 脚本
转自:http://jianjian.blog.51cto.com/35031/395468 这些是软件包安装前后自动运行的可执行脚本. 统称为控制文件, 是 Deian 软件包的"控制&q ...
- linux设备驱动概述,王明学learn
linux设备驱动学习-1 本章节主要学习有操作系统的设备驱动和无操作系统设备驱动的区别,以及对操作系统和设备驱动关系的认识. 一.设备驱动的作用 对设备驱动最通俗的解释就是“驱使硬件设备行动” .设 ...
- 学生成绩管理系统[C]
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<conio.h> #d ...
- UED
User Experience Design(用户体验设计),简称UED.UED是进行产品策划的主力之一,他们用自己的知识.经验.设计能力拿出设计方案. UED不只是互联网专家,还是行业专家.能够用自 ...
- dwz的form表单中url的变量替换
form表单中action的地址格式 “__URL__/edit/{xxx}”,大括号内的 “xxx” 就是变量名,主要功能是结合table组件一起使用. 下图中的删除.编辑.修改密码都是用了url变 ...
- xUtils,butterknife...处理findviewbyid
在写android中,经常要出现大量的findviewbyid et_path = (EditText) findViewById(R.id.et_path); tv_info = (TextVi ...
- Android常用控件之GridView与ExpandableListView的用法
概述 1.GridView:与ListView相比,可以显示多列,xml布局时其属性numColumns可以设置显示的列数. 2.ExpandableListView:与ListView相比,可以让每 ...
- WinForm支持拖拽效果
有一个MSDN客户提问在WinForm中如何实现拖拽效果——比如在WinForm中有一个Button,我要实现的效果是拖拽这个Button到目标位置后生成一个该控件的副本. 其实这个操作主要分成三步走 ...