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使用的小技巧,记录下来供以后查阅 由于机器是老婆的,创建新类的时候或者生成注释的时候全都是她的名字,避免弄混,需要设置一下: 设置创建新类时自动生成类或方法 ...
- 解决 CentOS网卡eth0启用不了问题
转自:http://www.centoscn.com/CentosBug/osbug/2014/0423/2850.html [root@localhost Desktop]# service net ...
- 信号量进程同步,王明学learn
信号量进程同步 一组并发进程进行互相合作.互相等待,使得各进程按一定的顺序执行的过程称为进程间的同步. 信号量在进程同步时初始值为:0 信号量在进程互斥时初始值为:大于0的 本章节主要使用信号量,使的 ...
- Codeforces Round #369 (Div. 2) C. Coloring Trees DP
C. Coloring Trees ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the pa ...
- 智能车学习(十八)——电机学习
一.C车电机选择 1.摘要: 因为C车模在四轮车的优势是有两个电机,可以进行主动差速,劣势是电机太弱了....所以如何选择电机,就是个钱的问题了,电机多一点,就比较好选,但是C车电机跑多了就 ...
- 关于MFC OpenGL环境配置的一点总结
复制include时要小心..看vs给你load哪一个..名字一样..东西可不一定一样哦 http://www.cppblog.com/wicbnu/archive/2010/09/30/128123 ...
- 【spring 后台跳转前台】使用ajax访问的后台,后台正常执行,返回数据,但是不能进入前台的ajax回调函数中
问题: 使用ajax访问的后台,后台正常执行,并且正常返回数据,但是不能进入前台的ajax回调函数中 问题展示: 问题解决: 最后发现是因为后台的方法并未加注解:@ResponseBody,导致方法 ...
- 关于解决haswell赛扬和奔腾 不能安装的问题
打开EFI\CLOVER\config.plist,并找到KernelAndKextPatches字段,在子集内插入下面代码. <key>FakeCPUID</key> < ...
- flv文件格式解析!!!
flv头 FLV header 总体上看,FLV包括文件头(File Header)和文件体(File Body)两部分,其中文件体由一系列的Tag组成. Signature: FLV 文件的前3个字 ...
- 一个android样本的过保护
前段时间处理一个android样本,样本本身作用不大,但是加了保护,遂做一个过保护的记录 通过dex2jar将dex转为jar文件的时候发现无法成功,通过抛出的异常可知,此处MainActivity: ...