Linux socket 地址及常用函數

來源:互聯網
上載者:User

IPv4通訊端地址結構:

 

#include <netinet/in.h>struct in_addr{     in_addr_t    s_addr;              /*32-bit,network byte orderd*/};struct sockaddr_in{   uint8           sin_len;   sa_family_t     sin_family;         /*AF_INET*/   in_port_t       sin_port;           /*16-bit,network byte ordered*/   struct in_addr  sin_addr;   char            sin_zero[8];};

s_addr可以為宏 INADDR_ANY

地址轉換函式:

 

 

#include <netinet/in.h>int inet_aton(const char *strptr, struct in_addr *addrptr);char *inet_ntoa(struct in_addr inaddr);

 

inet_aton將strptr所指的C字串轉換成一個32位的網路位元組序二進位值,並通過指標addrptr來儲存。若成功則返回1,否則返回0。

ps:gcc編譯時間,如果用--std=c99選項,編譯器會給出警告:“warning: implicit declaration of function ‘inet_aton’”,可以用--std=gnu99代替--std=c99,原因在這:http://stackoverflow.com/questions/1783792/why-does-gcc-report-implicit-declaration-of-function-round

 

inet_ntoa將32位的網路位元組序二進位IPv4地址轉換成相應的點分十進位數串。該函數傳回值指向一個靜態記憶體地區。所以是不可重新進入。如果你要用到這個返回的字串的話,最好自己拷貝出來。

位元組排序函數:

 

uint16_t htons(uint16_t host16bitvalue);uint32_t htonl(uint32_t host32bitvalue);                                                      /*返回網路位元組序的值*/uint16_t ntohs(uint16_t net16bitvalue);uint32_t ntohl(uint32_t net32bitvalue);                                                      /*返回主機位元組序的值*/

16:表示是16bit的值;32:表示是32bit的值;

 

s:短整數,即16bit; l:長整數,即32bit;

h:本地主機位元組; n:網路位元組;

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.