《深入理解计算机系统》读书笔记

来源:互联网 发布:java throw try catch 编辑:程序博客网 时间:2024/05/29 04:34

网络编程

IP地址是一个32为无符号整数,IP地址存放在IP地址结构体
struct in_addr{   unsigned int s_addr;       //32位ip地址,使用大端字节顺序 }; 

TCP/IP规定统一的网络字节顺序(大端字节顺序),因为主机字节顺序(host byte order)是小端法,所以必须有函数用于转换。htonl函数和ntohl是32位整数,short是16位整数
#include <netinet/in.h>unsigned long int htonl(unsigned long int hostlong);//将long int的主机字节转换为网络字节顺序unsigned short int htons(unsigned short int hostshort);//将short int的主机字节转换为网络字节顺序unsigned long int ntohl(unsigned long int netlong);//将long int类型的网络字节转为主机字节unsigned short int ntohs(unsigned short int netshort);//将long int类型的网络字节转为主机字节

类似128.2.194.242是地址0x8002c2f2的点分十进制表示。程序使用inet_aton和inet_ntoa函数来实现IP地址和点分十进制的转换。“n”代表的是网络Network,“a”代表应用,“to”表示转换。
#include <arpa/inet.h>int inet_aton(const char *cp, struct in_addr *inp);//将点分十进制串cp转换为网络字节顺序,成功返回1,出错返回0char *inet_ntoa(struct in_addr in);//将网络字节顺序的IP地址转换为一个点十进制串

域名集合和IP地址集合的映射关系,通过分布在时间范围内的数据库DNS(Domin Name System域名系统)维护,每个主机条目就是一个域名和IP地址的等价类。
//使用host entry形式保存映射关系struct hostent{  char *h_name;//主机里的官方域名  char **h_aliases;//域名数组  int  h_addrtype;//Host地址类型(AF_INET)  int  h_length;//地址长度,单位是byte  char **h_addr_list;//in_addr结构体的数组};



1 0