socket编程常见宏定义和数据结构

本文详细介绍了socket编程中的宏定义,包括SO_DEBUG、SO_REUSEADDR等,以及相关数据结构如struct sockaddr、struct sockaddr_in等。这些定义和结构在设置套接字选项、地址操作等方面起着关键作用,对于理解和使用socket编程至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 socket.h 宏定义

/*
 * For setsockopt(2)
 *
 * This defines are ABI conformant as far as Linux supports these ...
 */
#define SOL_SOCKET    0xffff

#define SO_DEBUG    0x0001    /* Record debugging information.  */
#define SO_REUSEADDR    0x0004    /* Allow reuse of local addresses.  */
#define SO_KEEPALIVE    0x0008    /* Keep connections alive and send
                   SIGPIPE when they die.  */
#define SO_DONTROUTE    0x0010    /* Don't do local routing.  */
#define SO_BROADCAST    0x0020    /* Allow transmission of
                   broadcast messages.  */
#define SO_LINGER    0x0080    /* Block on close of a reliable
                   socket to transmit pending data.  */
#define SO_OOBINLINE 0x0100    /* Receive out-of-band data in-band.  */
#if 0
To add: #define SO_REUSEPORT 0x0200    /* Allow local address and port reuse.  */
#endif

#define SO_TYPE        0x1008    /* Compatible name for SO_STYLE.  */
#define SO_STYLE    SO_TYPE    /* Synonym */
#define SO_ERROR    0x1007    /* get error status and clear */
#define SO_SNDBUF    0x1001    /* Send buffer size. */
#define SO_RCVBUF    0x1002    /* Receive buffer. */
#define SO_SNDLOWAT    0x1003    /* send low-water mark */
#define SO_RCVLOWAT    0x1004    /* receive low-water mark */
#define SO_SNDTIMEO    0x1005    /* send timeout */
#define SO_RCVTIMEO     0x1006    /* receive timeout */
#define SO_ACCEPTCONN    0x1009
#define SO_PROTOCOL    0x1028    /* protocol type */
#define SO_DOMAIN    0x1029    /* domain/socket family */

/* linux-specific, might as well be the same as on i386 */
#define SO_NO_CHECK    11
#define SO_PRIORITY    12
#define SO_BSDCOMPAT    14

#define SO_PASSCRED    17
#define SO_PEERCRED    18

/* Socket filtering */
#define SO_ATTACH_FILTER        26
#define SO_DETACH_FILTER        27

#define SO_PEERNAME             28
#define SO_TIMESTAMP        29
#define SCM_TIMESTAMP        SO_TIMESTAMP

#define SO_PEERSEC        30
#define SO_SNDBUFFORCE        31
#define SO_RCVBUFFORCE        33
#define SO_PASSSEC        34
#define SO_TIMESTAMPNS        35
#define SCM_TIMESTAMPNS        SO_TIMESTAMPNS

#define SO_MARK            36

#define SO_TIMESTAMPING        37
#define SCM_TIMESTAMPING    SO_TIMESTAMPING

#define SO_RXQ_OVFL             40

/** sock_type - Socket types
 *
 * Please notice that for binary compat reasons MIPS has to
 * override the enum sock_type in include/linux/net.h, so
 * we define ARCH_HAS_SOCKET_TYPES here.
 *
 * @SOCK_DGRAM - datagram (conn.less) socket
 * @SOCK_STREAM - stream (connection) socket
 * @SOCK_RAW - raw socket
 * @SOCK_RDM - reliably-delivered message
 * @SOCK_SEQPACKET - sequential packet socket
 * @SOCK_PACKET - linux specific way of getting packets at the dev level.
 *          For writing rarp and other similar things on the user level.
 */
enum sock_type {
    SOCK_DGRAM    = 1,
    SOCK_STREAM    = 2,
    SOCK_RAW    = 3,
    SOCK_RDM    = 4,
    SOCK_SEQPACKET    = 5,
    SOCK_DCCP    = 6,
    SOCK_PACKET    = 10,
};

#define SOCK_MAX (SOCK_PACKET + 1)
/* Mask which covers at least up to SOCK_MASK-1.  The
 *  * remaining bits are used as flags. */
#define SOCK_TYPE_MASK 0xf

/* Flags for socket, socketpair, paccept */
#define SOCK_CLOEXEC    O_CLOEXEC
#define SOCK_NONBLOCK    O_NONBLOCK


/* Address to accept any incoming messages. */
#define    INADDR_ANY        ((unsigned long int) 0x00000000)

/* Address to send to all hosts. */
#define    INADDR_BROADCAST    ((unsigned long int) 0xffffffff)

/* Address indicating an error return. */
#define    INADDR_NONE        ((unsigned long int) 0xffffffff)

/* Network number for local host loopback. */
#define    IN_LOOPBACKNET        127

/* Address to loopback in software to local host.  */
#define    INADDR_LOOPBACK        0x7f000001    /* 127.0.0.1   */
#define    IN_LOOPBACK(a)        ((((long int) (a)) & 0xff000000) == 0x7f000000)

/* Defines for Multicast INADDR */
#define INADDR_UNSPEC_GROUP       0xe0000000U    /* 224.0.0.0   */
#define INADDR_ALLHOSTS_GROUP     0xe0000001U    /* 224.0.0.1   */
#define INADDR_ALLRTRS_GROUP    0xe0000002U    /* 224.0.0.2 */
#define INADDR_MAX_LOCAL_GROUP  0xe00000ffU    /* 224.0.0.255 */

二 types.h中类型宏

/* bsd */
typedef unsigned char        u_char;
typedef unsigned short        u_short;
typedef unsigned int        u_int;
typedef unsigned long        u_long;

/* sysv */
typedef unsigned char        unchar;
typedef unsigned short        ushort;
typedef unsigned int        uint;
typedef unsigned long        ulong;

#ifndef __BIT_TYPES_DEFINED__
#define __BIT_TYPES_DEFINED__

typedef        __u8        u_int8_t;
typedef        __s8        int8_t;
typedef        __u16        u_int16_t;
typedef        __s16        int16_t;
typedef        __u32        u_int32_t;
typedef        __s32        int32_t;

#endif /* !(__BIT_TYPES_DEFINED__) */

typedef        __u8        uint8_t;
typedef        __u16        uint16_t;
typedef        __u32        uint32_t;

#if defined(__GNUC__)
typedef        __u64        uint64_t;
typedef        __u64        u_int64_t;
typedef        __s64        int64_t;
#endif

/* this is a special 64bit data type that is 8-byte aligned */
#define aligned_u64 __u64 __attribute__((aligned(8)))
#define aligned_be64 __be64 __attribute__((aligned(8)))
#define aligned_le64 __le64 __attribute__((aligned(8)))

typedef struct {
    int counter;
} atomic_t;


三 socket数据结构

typedef unsigned short    sa_family_t;

/*
 *    1003.1g requires sa_family_t and that sa_data is char.
 */
 
struct sockaddr {
    sa_family_t    sa_family;    /* address family, AF_xxx    */
    char        sa_data[14];    /* 14 bytes of protocol address    */
};

struct in_addr {
    __be32    s_addr;
};

/* Structure describing an Internet (IP) socket address. */
#define __SOCK_SIZE__    16        /* sizeof(struct sockaddr)    */
struct sockaddr_in {
  sa_family_t        sin_family;    /* Address family        */
  __be16        sin_port;    /* Port number            */
  struct in_addr    sin_addr;    /* Internet address        */

  /* Pad to size of `struct sockaddr'. */
  unsigned char        __pad[__SOCK_SIZE__ - sizeof(short int) - sizeof(unsigned short int) - sizeof(struct in_addr)];
};


struct net {
    atomic_t        count;        /* To decided when the network
                         *  namespace should be freed.
                         */
#ifdef NETNS_REFCNT_DEBUG
    atomic_t        use_count;    /* To track references we
                         * destroy on demand
                         */
#endif
    spinlock_t        rules_mod_lock;

    struct list_head    list;        /* list of network namespaces */
    struct list_head    cleanup_list;    /* namespaces on death row */
    struct list_head    exit_list;    /* Use only net_mutex */

    struct proc_dir_entry     *proc_net;
    struct proc_dir_entry     *proc_net_stat;

#ifdef CONFIG_SYSCTL
    struct ctl_table_set    sysctls;
#endif

    struct sock         *rtnl;            /* rtnetlink socket */
    struct sock        *genl_sock;

    struct list_head     dev_base_head;
    struct hlist_head     *dev_name_head;
    struct hlist_head    *dev_index_head;

    /* core fib_rules */
    struct list_head    rules_ops;


    struct net_device       *loopback_dev;          /* The loopback */
    struct netns_core    core;
    struct netns_mib    mib;
    struct netns_packet    packet;
    struct netns_unix    unx;
    struct netns_ipv4    ipv4;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
    struct netns_ipv6    ipv6;
#endif
#if defined(CONFIG_IP_DCCP) || defined(CONFIG_IP_DCCP_MODULE)
    struct netns_dccp    dccp;
#endif
#ifdef CONFIG_NETFILTER
    struct netns_xt        xt;
#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE)
    struct netns_ct        ct;
#endif
    struct sock        *nfnl;
    struct sock        *nfnl_stash;
#endif
#ifdef CONFIG_WEXT_CORE
    struct sk_buff_head    wext_nlevents;
#endif
    struct net_generic __rcu    *gen;

    /* Note : following structs are cache line aligned */
#ifdef CONFIG_XFRM
    struct netns_xfrm    xfrm;
#endif
};
/* Init's network namespace */
extern struct net init_net;

/* This is the per-socket lock.  The spinlock provides a synchronization
 * between user contexts and software interrupt processing, whereas the
 * mini-semaphore synchronizes multiple users amongst themselves.
 */
typedef struct {
    spinlock_t        slock;
    int            owned;
    wait_queue_head_t    wq;
    /*
     * We express the mutex-alike socket_lock semantics
     * to the lock validator by explicitly managing
     * the slock as a lock variant (in addition to
     * the slock itself):
     */
#ifdef CONFIG_DEBUG_LOCK_ALLOC
    struct lockdep_map dep_map;
#endif
} socket_lock_t;

/**
 *    struct sock_common - minimal network layer representation of sockets
 *    @skc_node: main hash linkage for various protocol lookup tables
 *    @skc_nulls_node: main hash linkage for TCP/UDP/UDP-Lite protocol
 *    @skc_refcnt: reference count
 *    @skc_tx_queue_mapping: tx queue number for this connection
 *    @skc_hash: hash value used with various protocol lookup tables
 *    @skc_u16hashes: two u16 hash values used by UDP lookup tables
 *    @skc_family: network address family
 *    @skc_state: Connection state
 *    @skc_reuse: %SO_REUSEADDR setting
 *    @skc_bound_dev_if: bound device index if != 0
 *    @skc_bind_node: bind hash linkage for various protocol lookup tables
 *    @skc_portaddr_node: second hash linkage for UDP/UDP-Lite protocol
 *    @skc_prot: protocol handlers inside a network family
 *    @skc_net: reference to the network namespace of this socket
 *
 *    This is the minimal network layer representation of sockets, the header
 *    for struct sock and struct inet_timewait_sock.
 */
struct sock_common {
    /*
     * first fields are not copied in sock_copy()
     */
    union {
        struct hlist_node    skc_node;
        struct hlist_nulls_node skc_nulls_node;
    };
    atomic_t        skc_refcnt;
    int            skc_tx_queue_mapping;

    union  {
        unsigned int    skc_hash;
        __u16        skc_u16hashes[2];
    };
    unsigned short        skc_family;
    volatile unsigned char    skc_state;
    unsigned char        skc_reuse;
    int            skc_bound_dev_if;
    union {
        struct hlist_node    skc_bind_node;
        struct hlist_nulls_node skc_portaddr_node;
    };
    struct proto        *skc_prot;
#ifdef CONFIG_NET_NS
    struct net         *skc_net;
#endif
};

/**
  *    struct sock - network layer representation of sockets
  *    @__sk_common: shared layout with inet_timewait_sock
  *    @sk_shutdown: mask of %SEND_SHUTDOWN and/or %RCV_SHUTDOWN
  *    @sk_userlocks: %SO_SNDBUF and %SO_RCVBUF settings
  *    @sk_lock:    synchronizer
  *    @sk_rcvbuf: size of receive buffer in bytes
  *    @sk_wq: sock wait queue and async head
  *    @sk_dst_cache: destination cache
  *    @sk_dst_lock: destination cache lock
  *    @sk_policy: flow policy
  *    @sk_rmem_alloc: receive queue bytes committed
  *    @sk_receive_queue: incoming packets
  *    @sk_wmem_alloc: transmit queue bytes committed
  *    @sk_write_queue: Packet sending queue
  *    @sk_async_wait_queue: DMA copied packets
  *    @sk_omem_alloc: "o" is "option" or "other"
  *    @sk_wmem_queued: persistent queue size
  *    @sk_forward_alloc: space allocated forward
  *    @sk_allocation: allocation mode
  *    @sk_sndbuf: size of send buffer in bytes
  *    @sk_flags: %SO_LINGER (l_onoff), %SO_BROADCAST, %SO_KEEPALIVE,
  *           %SO_OOBINLINE settings, %SO_TIMESTAMPING settings
  *    @sk_no_check: %SO_NO_CHECK setting, wether or not checkup packets
  *    @sk_route_caps: route capabilities (e.g. %NETIF_F_TSO)
  *    @sk_route_nocaps: forbidden route capabilities (e.g NETIF_F_GSO_MASK)
  *    @sk_gso_type: GSO type (e.g. %SKB_GSO_TCPV4)
  *    @sk_gso_max_size: Maximum GSO segment size to build
  *    @sk_lingertime: %SO_LINGER l_linger setting
  *    @sk_backlog: always used with the per-socket spinlock held
  *    @sk_callback_lock: used with the callbacks in the end of this struct
  *    @sk_error_queue: rarely used
  *    @sk_prot_creator: sk_prot of original sock creator (see ipv6_setsockopt,
  *              IPV6_ADDRFORM for instance)
  *    @sk_err: last error
  *    @sk_err_soft: errors that don't cause failure but are the cause of a
  *              persistent failure not just 'timed out'
  *    @sk_drops: raw/udp drops counter
  *    @sk_ack_backlog: current listen backlog
  *    @sk_max_ack_backlog: listen backlog set in listen()
  *    @sk_priority: %SO_PRIORITY setting
  *    @sk_type: socket type (%SOCK_STREAM, etc)
  *    @sk_protocol: which protocol this socket belongs in this network family
  *    @sk_peer_pid: &struct pid for this socket's peer
  *    @sk_peer_cred: %SO_PEERCRED setting
  *    @sk_rcvlowat: %SO_RCVLOWAT setting
  *    @sk_rcvtimeo: %SO_RCVTIMEO setting
  *    @sk_sndtimeo: %SO_SNDTIMEO setting
  *    @sk_rxhash: flow hash received from netif layer
  *    @sk_filter: socket filtering instructions
  *    @sk_protinfo: private area, net family specific, when not using slab
  *    @sk_timer: sock cleanup timer
  *    @sk_stamp: time stamp of last packet received
  *    @sk_socket: Identd and reporting IO signals
  *    @sk_user_data: RPC layer private data
  *    @sk_sndmsg_page: cached page for sendmsg
  *    @sk_sndmsg_off: cached offset for sendmsg
  *    @sk_send_head: front of stuff to transmit
  *    @sk_security: used by security modules
  *    @sk_mark: generic packet mark
  *    @sk_classid: this socket's cgroup classid
  *    @sk_write_pending: a write to stream socket waits to start
  *    @sk_state_change: callback to indicate change in the state of the sock
  *    @sk_data_ready: callback to indicate there is data to be processed
  *    @sk_write_space: callback to indicate there is bf sending space available
  *    @sk_error_report: callback to indicate errors (e.g. %MSG_ERRQUEUE)
  *    @sk_backlog_rcv: callback to process the backlog
  *    @sk_destruct: called at sock freeing time, i.e. when all refcnt == 0
 */
struct sock {
    /*
     * Now struct inet_timewait_sock also uses sock_common, so please just
     * don't add nothing before this first member (__sk_common) --acme
     */
    struct sock_common    __sk_common;
#define sk_node            __sk_common.skc_node
#define sk_nulls_node        __sk_common.skc_nulls_node
#define sk_refcnt        __sk_common.skc_refcnt
#define sk_tx_queue_mapping    __sk_common.skc_tx_queue_mapping

#define sk_copy_start        __sk_common.skc_hash
#define sk_hash            __sk_common.skc_hash
#define sk_family        __sk_common.skc_family
#define sk_state        __sk_common.skc_state
#define sk_reuse        __sk_common.skc_reuse
#define sk_bound_dev_if        __sk_common.skc_bound_dev_if
#define sk_bind_node        __sk_common.skc_bind_node
#define sk_prot            __sk_common.skc_prot
#define sk_net            __sk_common.skc_net
    kmemcheck_bitfield_begin(flags);
    unsigned int        sk_shutdown  : 2,
                sk_no_check  : 2,
                sk_userlocks : 4,
                sk_protocol  : 8,
                sk_type      : 16;
    kmemcheck_bitfield_end(flags);
    int            sk_rcvbuf;
    socket_lock_t        sk_lock;
    /*
     * The backlog queue is special, it is always used with
     * the per-socket spinlock held and requires low latency
     * access. Therefore we special case it's implementation.
     */
    struct {
        struct sk_buff *head;
        struct sk_buff *tail;
        int len;
    } sk_backlog;
    struct socket_wq    *sk_wq;
    struct dst_entry    *sk_dst_cache;
#ifdef CONFIG_XFRM
    struct xfrm_policy    *sk_policy[2];
#endif
    spinlock_t        sk_dst_lock;
    atomic_t        sk_rmem_alloc;
    atomic_t        sk_wmem_alloc;
    atomic_t        sk_omem_alloc;
    int            sk_sndbuf;
    struct sk_buff_head    sk_receive_queue;
    struct sk_buff_head    sk_write_queue;
#ifdef CONFIG_NET_DMA
    struct sk_buff_head    sk_async_wait_queue;
#endif
    int            sk_wmem_queued;
    int            sk_forward_alloc;
    gfp_t            sk_allocation;
    int            sk_route_caps;
    int            sk_route_nocaps;
    int            sk_gso_type;
    unsigned int        sk_gso_max_size;
    int            sk_rcvlowat;
#ifdef CONFIG_RPS
    __u32            sk_rxhash;
#endif
    unsigned long         sk_flags;
    unsigned long            sk_lingertime;
    struct sk_buff_head    sk_error_queue;
    struct proto        *sk_prot_creator;
    rwlock_t        sk_callback_lock;
    int            sk_err,
                sk_err_soft;
    atomic_t        sk_drops;
    unsigned short        sk_ack_backlog;
    unsigned short        sk_max_ack_backlog;
    __u32            sk_priority;
    struct pid        *sk_peer_pid;
    const struct cred    *sk_peer_cred;
    long            sk_rcvtimeo;
    long            sk_sndtimeo;
    struct sk_filter __rcu    *sk_filter;
    void            *sk_protinfo;
    struct timer_list    sk_timer;
    ktime_t            sk_stamp;
    struct socket        *sk_socket;
    void            *sk_user_data;
    struct page        *sk_sndmsg_page;
    struct sk_buff        *sk_send_head;
    __u32            sk_sndmsg_off;
    int            sk_write_pending;
#ifdef CONFIG_SECURITY
    void            *sk_security;
#endif
    __u32            sk_mark;
    u32            sk_classid;
    void            (*sk_state_change)(struct sock *sk);
    void            (*sk_data_ready)(struct sock *sk, int bytes);
    void            (*sk_write_space)(struct sock *sk);
    void            (*sk_error_report)(struct sock *sk);
      int            (*sk_backlog_rcv)(struct sock *sk,
                          struct sk_buff *skb);  
    void                    (*sk_destruct)(struct sock *sk);
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值