Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux Socket 位址結構與常用函式整理

IPv4 通訊位址結構

#include <netinet/in.h>

struct in_addr
{
    in_addr_t s_addr;                  /* 32-bit, network byte ordered */
};

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 把字串轉成 32 位元網路位元組序的位元值並透過 addrptr 存回,成功回傳 1,失敗回傳 0。

ps:用 --std=c99 編譯時,編譯器會警告「implicit declaration of function 'inet_aton'」,改用 --std=gnu99 即可解決。

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 表示 16 位元、32 表示 32 位元;s 代表 short(16 位元)、l 代表 long(32 位元);h 是 host(本機位元組序)、n 是 network(網路位元組序)。合起來看,htons 就是「host to network short」,ntohl 就是「network to host long」,不必死背。

Copyright © Linux教程網 All Rights Reserved