歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux C網絡常用結構體及函數匯總

Linux C網絡常用結構體及函數匯總

日期:2017/3/1 10:45:42   编辑:Linux編程

一。結構體


1.
struct sockaddr {
unsigned short sa_family; /* address family, AF_xxx */
char sa_data[14]; /* 14 bytes of protocol address */
};
共2+14=16字節

2.
#include <netinet/in.h>

struct sockaddr_in {
short sin_family;   // e.g. AF_INET 協議族
unsigned short sin_port;   // e.g. htons(3490) 端口號(網絡字節序)
struct in_addr sin_addr;   // IP地址
unsigned char sin_zero[8];   // 為了讓sockaddr與sockaddr_in兩個數據結構保持大小相同而保留的空字節
};

共2+2+4+8=16字節
(1)Internet上數據以高位字節優先順序在網絡上傳輸
(2)sin_zero應該用bzero()或memset()函數將其置為零
(3)sin_family通常被賦AF_INET;sin_port和 sin_addr應該轉換成為網絡字節優先順序;而sin_addr則不需要轉換。

sockaddr_in和sockaddr是並列的結構,指向sockaddr_in的結構體的指針也可以指向
sockaddr的結構體,並代替它.

3. struct in_addr {
unsigned long s_addr; // load with inet_aton()
};

  共4字節

4.

   struct hostent {
   char *  h_name;   //地址的正式名稱
   char **   h_aliases;   // 空字節-地址的預備名稱的指針
   int    h_addrtype;   //地址類型; 通常是AF_INET
   int    h_length;    // 地址的比特長度
   char **  h_addr_list;   // 零字節-主機網絡地址指針。網絡字節順序
   };

 #define h_addr h_addr_list[0]   //h_addr_list中的第一地址

二.轉換函數

1. #include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

2.inet_ntoa

#include <arpa/inet.h>

char *inet_ntoa (struct in_addr)

將網絡主機地址轉為網絡標准點分格式的字符串。

3.inet_addr

#include <arpa/inet.h>

in_addr_t inet_addr(const char *cp);
將字符串cp(標准的IPV4點分十進制格式地址)轉為一個合適的可作為網絡地址的整數。

其中<netinet/in.h>

typedef uint32_t in_addr_t;

而<stdint.h>中

:typedef unsigned int uint32_t;

所以:in_addr_t ->unsigned int

4.

gethostbyname

gethostbyaddr

#include <netdb.h>


struct hostent *   gethostbyaddr(const void *addr, socklen_t len, int type);

struct hostent *   gethostbyname(const char *name);


5.

socket

#Include <sys/socket.h>

int socket(int domain, int type, int protocol);

connect

int connect(int socket, const struct sockaddr *address,
socklen_t address_len);

bind

int bind(int socket, const struct sockaddr *address,
socklen_t address_len);

listen

int listen(int socket, int backlog);

Copyright © Linux教程網 All Rights Reserved