socket網絡編程第一講

先總結一下求職面試必看的幾本書:《編程之美》、《劍指offer》、《Unix環境編程》、《Unix網絡編程》、《POSIX多線程編程》,突然感覺心裏很踏實,不再像以前迷茫,終於知道計算機專業畢業的我到底能幹什麼,既然這樣就認認真真的學習吧,爭取拿到bat的實習offer,加油。

 

網絡字節序:

由於不同的計算機系統採用不同的字節序存儲數據,同樣一個4字節的32位整數,在內存中存儲的方式就不同字節序分爲小尾字節序(Little Endian)和大尾字節序(Big Endian), Intel處理器大多數使用小尾字節序, Motorola處理器大多數使用大尾(Big Endian)字節序;

 

TCP/IP各層協議將字節序定義爲大尾,因此TCP/IP協議中使用的字節序通常稱之爲網絡字節序。

 

1、將IP轉換成16進制數

/*************************************************************************

> File Name: my_atoh.c

> Author: Comst

> Mail:[email protected] 

> Created Time: Sat 07 Feb 2015 04:56:54 PM CST

 ************************************************************************/

 

#include<stdio.h>

#include<string.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#define IP "180.97.33.107"// B461216B

int main(int argc, char* argv[])

{

 

struct in_addr addr ;

memset(&addr, 0, sizeof(addr));

inet_aton(IP, &addr);

memset(&addr, 0, sizeof(addr));

addr.s_addr = inet_addr(IP);

char* pstr = inet_ntoa(addr);

return 0 ;

}

2、查看域名的詳細信息

/*************************************************************************

> File Name: my_host.c

> Author: Comst

> Mail:[email protected] 

> Created Time: Sat 07 Feb 2015 05:23:46 PM CST

 ************************************************************************/

 

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#include<netdb.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

int main(int argc, char* argv[])

{

struct hostent* pent ;

int i ;

pent = gethostbyname(argv[1]) ;

if(pent == NULL)

{

perror("host");

}

printf("h_name: %s\n", pent ->h_name);

for(i = 0; pent ->h_aliases[i] != NULL; i ++)

{

printf("aliase %d: %s\n", i, pent ->h_aliases[i]);

}

printf("addr_type: %d, len: %d\n", pent ->h_addrtype, pent ->h_length );

for(i = 0; pent ->h_addr_list[i] != NULL; i ++)

{

printf("ip %d: %s\n ", i, inet_ntoa( *(struct in_addr*)pent ->h_addr_list[i]) );

}

 

return 0 ;

}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章