• 套接字地址结构


    一、套接字地址的用途

       套接字可以在两个方向上传递,从进程到内核和从内核到进程。其中,从进程到内核方向的传递是值-结果参数的一个例子,地址转换函数在地址的文本表达和他们存放的套接字地址结构中的二进制值之间进行转换。多数现存的代码使用 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);
  • 相关阅读:
    appium之adb常用命令
    测试基础之等价类
    selenium之CSS定位
    括号序列的最小代价
    Spark相对于MapReduce的优势
    Cache系统设计
    [京东2017实习生笔试] 终结者C
    [京东2017实习生笔试] 通过考试
    [hihoCoder] 1078. 线段树的区间修改
    [转载] 一步一步理解线段树
  • 原文地址:https://www.cnblogs.com/yinguojin/p/14552992.html
Copyright © 2020-2023  润新知