套接字编程简介

3.2 套接字地址结构

3.2.1 IPv4 套接字地址结构

struct in_addr{
    in_addr_t s_addr; // 4 bytes
};
struct sockaddr_in{
    uint8_t sin_len;
    sa_family_t sin_family;
    in_port_t sin_port;
    
    struct in_addr sin_addr;
    char sin_zero[8];
};

3.2.2 通用套接字地址结构

struct sockaddr{
    uint8_t sa_len;
    sa_family_t sa_family;
    char sa_data[14]; 
};
struct sockaddr_in serv;
bind (sockfd, (struct sockaddr *) &serv, sizeof (serv)); // 强制类型转换

3.2.3 IPv6套接字地址结构

struct in6_addr {
    uint8_t s6_addr[16];
};
struct sockaddr_in6{
    uint8_t sin6_len;
    sa_family_t sin6_family;
    in_port_t sin6_port;
    
    uint32_t sin6_flowinfo; 
    
    struct in6_addr sin6_addr;
    uint32_t sin6_scope_id; 
};

3.2.4 新的通用套接字地址结构

struct sockaddr_storage{
    uint8_t ss_len;
    sa_family_t ss_family; 
};

3.4 字节排序函数

uint16_t htons(uint16_t ); 
uint32_t htonl(uint32_t );
uint16_t ntohs(uint16_t ); 
uint32_t ntohl(uint32_t );

3.5 字节操纵函数

// 更简洁,不容易出错
void bzero(void* dest, size_t nbytes); 
void* memset(void* dest, int c, size_t len);

// 当src和dest重叠时,不出错
void bcopy(const void *src, void *dest, size_t nbytes); 
// 当src和dest重叠时,出错, 改用 memmove
void* memcpy(const void *dest, void *src, size_t nbytes);
// 当src和dest重叠时,不出错
void* memmove(void *dest, const void *src, size_t num);
int bcmp(const void* ptr1,  const void *ptr2, size_t nbytes); 
char *strcpy(char* dest, const char *src); // 遇到 '\0' 结束复制

3.7 inet_pton 和 inet_ntop

int inet_pton(int family, const char* strptr, void* addptr); 

const char* inet_ntop(int family, const void* addptr, char* strptr, size_t len); 

shiyang6017
158 声望59 粉丝

引用和评论

0 条评论