Linux网络编程 (获取ip地址 gethostbyname)
2016-03-23 11:14
621 查看
#include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netdb.h> #include<netinet/in.h> #include<string.h> #include<stdlib.h> #include<arpa/inet.h> int main(int argc,char *argv[]) { struct hostent *h; if(argc!=2) {/*检查命令行*/ fprintf(stderr,"usage:getipaddress"); exit(1); } if((h=gethostbyname(argv[1]))==NULL) { herror("gethostbyname\n"); exit(2); } printf("hostname is %s\n",h->h_name); printf("ip changed %s\n",inet_ntoa( *((struct in_addr*)h->h_addr) ) ); return 0; }
需要使用的结构体
struct in_addr { __be32 s_addr; }; //ip地址 struct hostent *gethostbyname(const char *name); //这个函数的传入值是域名或者主机名,例如"www.google.cn"等等。 //传出值,是一个hostent的结构。如果函数调用失败,将返回NULL。 //所在头文件<sys/socket.h> struct hostent{ char * h_name; char ** h_aliases; short h_addrtype; short h_length; char ** h_addr_list; }; //主机信息 #define h_addr h_addr_list[0] char *inet_ntoa (struct in_addr); //返回点分十进制的字符串在静态内存中的指针。 //所在头文件:<arpa/inet.h>
相关文章推荐
- mousedos网络批量部署xp
- 移动端高清、多屏适配方案 [来源:http://div.io/topic/1092]
- Linux服务器上监控网络带宽的18个常用命令
- 网络基础
- 【Web优化】Yslow优化法则(一)最小化HTTP请求数
- 3月第2周网络安全报告:高危漏洞数量涨幅超126%
- Qt 解析网络数据出现ssl错误
- 客户端 HttpUtils.java
- xmlhttprequest请求
- 物理层、mac层、IP层、TCP(UDP)帧格式-------未完待续
- Android OkHttp完全解析 是时候来了解OkHttp了
- Stanford机器学习---第五讲. 神经网络的学习 Neural Networks learning
- [置顶] SSL安全证书Let's Encrypt安装使用教程(启用https)
- 为什么各大网站都纷纷用起了https?哪些网站需要https(SSL证书)
- tcp/ip ---IP路由选择
- Android 一个改善的okHttp封装库
- 使用Jmeter进行http接口测试
- HTTP协议和HTTPS协议初探
- tcp/ip --IP:网际协议
- 复杂mapreduce程序 分析http服务器数据