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. ...
随机推荐
- JQuery 操作对象的属性值
通过JQuery去操作前台对象(div,span...)的属性是很常见的事情,本文就简单的介绍几种操作情形. 1):通过属性值去获取对象 2):用JQuery去修改对象的属性值 3):获取并修改对象的 ...
- windows下mongodb安装与使用整理
一.首先安装mongodb 1.下载地址:http://www.mongodb.org/downloads 2.解压缩到自己想要安装的目录,比如d:\mongodb 3.创建文件夹d:\mongodb ...
- Emacs 之列编辑模式
// */ // ]]> Emacs 之 列编辑模式 Table of Contents 1. Emacs 下列编辑模式常用命令 2. 可以参考 1 Emacs 下列编辑模式常用命令 先mark ...
- FastDFS实现文件上传下载实战
正好,淘淘商城讲这一块的时候,我又想起来当时老徐让我写过一个关于实现FastDFS实现文件上传下载的使用文档,当时结合我们的ITOO的视频系统和毕业论文系统,整理了一下,有根据网上查到的知识,总结了一 ...
- zookeeper源码分析三LEADER与FOLLOWER同步数据流程
根据二)中的分析,如果一台zookeeper服务器成为集群中的leader,那么一定是当前所有服务器中保存数据最多的服务器,所以在这台服务器成为leader之后,首先要做的事情就是与集群中的其它服务器 ...
- js 的一点用法
js 中的json对象,ajax返回数据dataType为json否则无法将数据转换成json对象 也就无法通过json字符串转换成对象object,那么他将始终是个字符串,也就无法进行 对象操作. ...
- BZOJ 3053 The Closest M Points
[题目分析] 典型的KD-Tree例题,求k维空间中的最近点对,只需要在判断的过程中加上一个优先队列,就可以了. [代码] #include <cstdio> #include <c ...
- 我的c++学习(1)hello world!
// texthello.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> using na ...
- Android App 性能优化实践
本文记录了Android App优化需要用到的工具和以及在实践中的Tips.也算对我这半年来部分工作的总结. 工具 Hierarchy Viewer 是 Android SDK 自带的 Layout ...
- Jenkins启动时报错:java.net.BindException: Address already in use: bind 解决方法
下载jenkins.war包后,进入Jenkins.war包目录下,运行java -jar jenkins.war时报端口被占用的错误:java.net.BindException: Address ...