ip相關知識
1. ip位址
ip位址用1個32為無符號整數表示。存在 ip位址結構中
structure in_addr
示例2:編寫dd2hex.c 將 點分十進位制 轉換為十六進製制
unix> ./dd2hex 128.2.194.242
0x8002c2f2
#include #include int main(int ac, char *agv)
3. ip位址與 網域名稱 的轉化
網際網路中為了相互通訊,為每台主機分配乙個ip位址。為了更加人性化,又為其定義了網域名稱。
這種 網域名稱與ip位址的對映 有dns(網域名稱系統) 維護。 以 主機條目結構 的形式 儲存在dns資料庫中。
其中 主機條目結構型別如下
struct hostent ;
#define h_addr h_addr_list[0]
#include
struct hostent*gethostbyname(const char * hostname);
引數為 網域名稱,如www.baidu.com
返回:非空指標
——成功,空指標——出錯,同時設定h_errno
struct hostent*gethostbyaddr(const char * addr, int len, 0);
返回:非空指標
——成功,空指標——出錯,同時設定h_errno
引數 addr為 ip位址(無符號整數),需進行強制轉換,如下, len ip位址(無符號整數)多為4個位元組
struct in_addraddr;
struct hostent *myhost;
myhost =gethostbyaddr((constchar*)&addr, sizeof(addr), af_inet);
hostinfo.c
#include #include #include #include int main(int argc, char **argv)
if(inet_aton(argv[1], &addr) != 0)//success 關鍵判斷語句 不為0表示 將ip位址點分形式轉化為 整數形式成功,說明輸入的為 ip位址,而非網域名稱
else
printf("offical hostname:%s\n", hostp->h_name);
for(pp = hostp->h_aliases; *pp != null;pp++)
printf("alias:%s\n",*pp);
for(pp = hostp->h_addr_list; *pp != null; pp++)
return 0;
}
測試1: ./hostinfowww.baidu.com
結果:by name
測試2: ./hostinfo128.2.205.216
結果:by addr
offical hostname:bluefish.ics.cs.cmu.edu
ip:128.2.205.216, 0x8002cdd8
深入理解計算機系統(網路程式設計)
include include include include include include typedef struct sockaddr sa int open clientfd char hostname,int port if hp gethostbyname hostname null ...
深入理解計算機系統 2
程式抽象流程 在c語言中 1 c預處理器 cpp 擴充套件源 插入所有用 include 命名指定的檔案,並擴充套件所有用 define 宣告指定的巨集。2 編譯器 ccl 產生兩個源 的彙編 名字命名分別為p1.s 3 彙編器 as 將彙編 轉化為二進位制目標 為p1.o 目標 是機器 的一種形式...
深入理解計算機系統 2
第一部分 程式結構和執行 我們對計算機系統的探索是從學習計算機本身開始的 它是由處理器和儲存器子系統組成 在核心部分 我們需要方法來表示基本資料型別 比如整數和實數運算的近似值 然後我們考慮機器級指令如何操作這樣的資料 以及編譯器如何將c程式翻譯成這樣的指令 接下來研究幾種實現處理器的方法 幫助我們...