首页 > 技术文章 > 套接字地址结构

yinguojin 2021-03-28 17:55 原文

一、套接字地址的用途

   套接字可以在两个方向上传递,从进程到内核和从内核到进程。其中,从进程到内核方向的传递是值-结果参数的一个例子,地址转换函数在地址的文本表达和他们存放的套接字地址结构中的二进制值之间进行转换。多数现存的代码使用 inet_addr 和 inet_ntoa 这两个函数,不过两个新函数 inet_pton 和 inet_ntop 同时适用于IPV4和IPV6。

 

二、套接字地址结构

   IPv4套接字地址结构

struct in_addr{
    in_addr_t s_addr;          /*32Bit  IPv4 address*/
};

struct sockaddr_in{
    uint8_t        sin_len;       /*套接字地址长度*/
    sa_family_t    sin_family;    /*地址族AF_INET*/
    in_port_t      sin_port;      /*16Bit port number*/
    
    struct in_addr sin_addr;      /*32Bit  IPv4 address*/
    char  sin_zero[8];            /*unused*/
};

  IPv6套接字地址结构

struct in6_addr{
    uint8_t s6_addr[16];          /*128Bit  IPv6 address*/
};

#define SIN6_LEN
struct sockaddr_in6{
    uint8_t        sin6_len;       /*套接字地址长度*/
    sa_family_t    sin6_family;    /*地址族AF_INET6*/
    in_port_t      sin6_port;      /*port number*/
    
    uint32_t   sin6_flowinfo;
    struct in6_addr sin6_addr;     /*IPv6 address*/
    uint32_t  sin6_scope_id;       /*set if interface for a scope*/
};

  通用地址结构

struct sockaddr_storage{
    uint8_t      ss_len;
    sa_family   ss_family;
};

 

三、一个完整的TCP客户端/服务器程序所需的基本套接字函数

#include <sys/socket.h>
#include <unistd.h>

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

int connect( int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);

int bind( int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);

int listen( int sockfd, int backlog);

int accept( int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);

pid_t fork(void);

int close( int sockfd);

 

推荐阅读