Linux网络编程系列-获取机器名和ip

来源:互联网 发布:seo ppt 编辑:程序博客网 时间:2024/05/01 02:10
[cpp] view plaincopy
  1. #include <netdb.h>  
  2. #include <arpa/inet.h>  
  3. using namespace std;  
  4.   
  5. int main() {  
  6.   int result = 0;  
  7.   char hostName[100];  
  8.   struct hostent* host = NULL;  
  9.   result = gethostname(hostName, 100);  
  10.   host = gethostbyname(hostName);  
  11.   char* ip =inet_ntoa(*((struct in_addr *)host->h_addr_list[0]));  
  12.   cout<< "hostname:" << hostName << ", ip:" << ip << endl;  
  13.   return 1;  
  14. }  

解析:

[cpp] view plaincopy
  1. struct hostent  
  2. {  
  3. char* h_name;       //主机的规范名  
  4. char** h_aliases;   //主机的别名  
  5. int h_addrtype;     //主机ip地址类型, AF_INET为ipv4, AF_INET6为ipv6  
  6. int h_length;       //主机ip地址长度  
  7. char** h_addr_list; //主机的ip地址,网络字节序  
  8. }  
字节序:整数的字节在内存中保存的顺序,little endian(符合人的思维,高位在地址高位存储,低位在地址低位存储,高低),big endian(计算机读取方便,低位在地址高位存储,高位在地址低位存储,低高),网络字节序是big endian方式。


[cpp] view plaincopy
  1. char* inet_ntoa(struct in_addr) //将网络字节序ip地址转为字符串  
  2. struct in_addr {  
  3.     in_addr_t s_addr;  
  4. };  
结构体in_addr 用来表示一个32位的IPv4地址,in_addr_t 为 32位的unsigned long,其字节顺序为网络字节序
0 0
原创粉丝点击