Linux C network _ to create a socket descriptor function

Linux uses socket function to create a socket descriptor.

#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);

If the function succeeds, it returns the socket descriptor, is a positive integer, if the function fails -1 is returned.

A function of various parameters as follows:

  • domain: socket protocol family, it supports Type Description Table, socket functions can support multiple network protocols, the protocol must be specified when using currently used.

socket functions support the protocol suite

Protocol family name description
AF_UNIX, AF_LOCAL Local interactive protocol
AF_INET IPv4 protocol
AF_INET6 IPv6 protocol
AF_IPX IPX-Novell Agreement
AF_NETLINK Kernel interface device protocol
AF_X25 ITU-T X.25 / ISO-8208 protocol
AF_AX25 Amateur Radio AX.25 protocol
AF_ATMPVC Original ATM access protocol
AF_APPLETALK Apple's Appletalk protocol
AF_PACKET Underlying packet interface
  • type: specifies the type of current socket, socket comprises a socket type support function SOCK_STREAM (data flow), SOCK_DGRAM (datagram), SOCK_SEQPACKET (sequential data packets), SOCK_RAW (raw socket), SOCK_RDM ( reliable message delivery), SOCK_PACKET (packet).
  • protocol: In addition to the use of raw sockets other than (usually set to 0, to use the default protocol created in the Linux system creates a socket in the kernel data structure when a socket, and then returns. a socket descriptor data structure identifying the socket. the socket connector data structure contains a variety of information, such as the other addresses, TCP receive buffer status and the like .TCP transmission protocol according to the data structure of the socket to control the content of this connection.

[Example 1] using the socket function to create a socket
application code calls socket function to create a socket, the socket using the protocol set AF_INET, the STREAM type socket, if the creation is successful, it returns the corresponding sleeve Sockets descriptor.

Examples of the application code as follows:

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
    int sockfd;  //定义套接口描述符
    if(sockfd = socket(AF_INET,SOCK_STREAM,0)<0)  //建立一个 socket
    {
        printf("创建套接字失败。\n");
        return 1;
    }
    else  //socket 创建成功
    {
        printf("套接字的ID是:%d\n", sockfd);
    }
    return 0;
}
Published 70 original articles · won praise 131 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_43239560/article/details/103129481