歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux socket 地址及常用函數

Linux socket 地址及常用函數

日期:2017/3/1 9:58:35   编辑:Linux編程

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 &nbsp; &nbsp;sin_family; &nbsp; &nbsp;/*AF_INET*/
in_port_t sin_port; &nbsp; &nbsp; /*16-bit,network byte ordered*/
struct in_addr &nbsp;sin_addr;
char &nbsp; &nbsp; &nbsp; &nbsp;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,原因在這裡。

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:網絡字節;

Copyright © Linux教程網 All Rights Reserved