socket main function introduction

1. The basic function of the socket
(1) socket function prototype

socket (to create a socket file descriptor)

The required header files

#include <sys/types.h>       

#include <sys/socket.h>

Function Description

Establish a socket file descriptor

Function prototype

int socket(int domain, int type, int protocol)

Incoming function value

domain

AF_INET: IPv4 protocol

AF_INET6: IPv6 protocol

AF_LOCAL: Unix domain protocol

AF_ROUTE: routing socket

AF_KEY: key socket

type

SOCKET_STREAM: Bidirectional Reliable data stream corresponding to TCP

SOCKET_DGRAM: two-way unreliable datagram corresponding UDP

SOCKET_RAW: provided below the transport layer protocol, can access the internal network interface, for example, receive and send ICMP packets

protocol

When this value needs to be set SOCKET_RAW type protocol type is described, other types can be set to 0

Function return value

Success: socket file descriptor

Failed: -1 failure reason stored in the error

 

Table 18-1 lists the combination when the socket call, the protocol suite (domain) and type (type) that may arise.

Table 18-1 socket in the protocol stack (Domain) and type (type) combination table

 

AF_INET

AF_INET6

AF_LOCAL

AF_ROUTE

AF_KEY

SOCK_STREAM

TCP

TCP

Yes

 

 

SOCK_DGRAM

UDP

UDP

Yes

 

 

SOCK_RAW

IPv4

IPv6

 

Yes

Yes

 

(2) bind function prototype

bind (a local protocol address with socket file descriptor)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

The protocol address and a socket file descriptor link

Function prototype

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

Incoming function value

sockfd

socket file descriptor

addr

my_addr point sockaddr structure that contains the IP address and port information, etc.

addrlen

Sockaddr structure size can be set to sizeof (struct sockaddr)

Function return value

Success: 0

Failed: -1 failure reason stored in the error

When you bind address using the bind function, you can specify the IP address and port number, you can specify one of them, even a not specified. Can use a wildcard address INADDR_ANY (macro definitions, which value is equal to 0), it notifies the kernel selects an IP address. Table 18-2 lists the settings in several ways socket address structure, but in practice, binding port number needs to be specified.

         Table 18-2 provided in several ways socket address structure       

Process specified

Explanation

IP addresses

port

Wildcard address INADDR_ANY

0

Kernel automatically selects an IP address and port number

Wildcard address INADDR_ANY

Non-0

Kernel automatically selects an IP address, port number specified process

Local IP Address

0

Specify the IP address of the process, the kernel automatically select a port number

Local IP Address

Non-0

Process specify the IP address and port number

 

(3) listen function prototype

listen (waiting for connection)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Waiting for connection

Function prototype

int listen(int sockfd, int backlog)

Incoming function value

sockfd

Listening socket file descriptor

backlog

The maximum number of connections queued socket

Function return value

Success: 0

Failed: -1 failure reason stored in the error

Special Note

For the listening socket file descriptor sockfd, the kernel to maintain two queues, respectively, did not complete the connection queue and queue connection has been completed, the two queues and no more than backlog

 

(4) connect function prototype

connect (establish socket connections)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Establish a socket connection

Function prototype

int connect(int sockfd, const struct sockaddr *serv_addr,

                   socklen_t addrlen)

Incoming function value

sockfd

socket file descriptor

serv_addr

Network address and port connections

addrlen

Sockaddr structure size can be set to sizeof (struct sockaddr)

Function return value

Success: 0

Failed: -1 failure reason stored in the error

Additional information

Three-way TCP handshake function connect excitation, the error returned the following situations:

① If the customer does not receive a response SYN sub-section (a total of 75 seconds, may be re-issued several times between SYN), then return ETIMEDOUT

② If the response to the customer's SYN is RST, indicates that the server host is not connected with the process of waiting on the specified port, the function returns an error ECONNREFUSED

③ If the client sends SYN triggered a destination unreachable ICMP error in the intermediate routers, core return EHOSTUNREACH or ENETUNREACH error (that is, ICMP error) to the process

 

(5) accept function prototypes

                accept (accepts the socket connection)

 

 

The required header files

#include <sys/types.h>     

#include <sys/socket.h>

Function Description

Accepts the socket connection and returns a new socket file descriptor, the original descriptor remains socket listen function used, and the new socket file descriptors for processing read and write operations connected

Function prototype

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)

Function parameter passing

sockfd: socket file descriptor

addrlen: addr size can be set to sizeof (struct sockaddr)

Outgoing function parameters

addr: fill in the remote host address data

Function return value

Success: The actual number of bytes read

Failed: -1, the error code stored in the error

Additional information

① accept function calls by the TCP server for blocking function that returns from the completed connection queue a connection; if the pair is empty, the process enters the blocked wait

② function returns the socket is already connected socket, but still listen listening socket function used

 

(6) close function prototype

close (close file descriptor socket connection)

The required header files

#include <unistd.h>

Function Description

Close connection socket file descriptor

Function prototype

int close(int sockfd)

Incoming function value

sockfd: socket file descriptor

Function return value

Success: 0

Failed: -1 failure reason stored in the error

Additional information

① close function is the default function socket set to "closed" mark, and immediately returned to the process, the socket can not be used for the process

② Under normal circumstances, lead to the four section Close termination sequences, but transmits queued data before termination

③ If the socket descriptor after calling close access count is greater than 0 (a plurality of processes share a socket under the same conditions), is not raised TCP termination sequence (i.e. sub-section does not send FIN)

 

(7) shutdown function prototype

shutdown (socket communication termination)

The required header files

#include <sys/socket.h>

Function Description

Termination socket communication

Function prototype

int shutdown(int s, int how)

Incoming function value

s

socket file descriptor

how

0 (SHUT_RD): read the closed socket connection half, it no longer receives data socket and remain in the receive buffer is now obsolete data

1 (SHUT_WR): write the closed socket connection half (half-off), but the data transmission will remain in the socket buffer is sent, followed by a TCP connection termination sequence, regardless of whether the access count is greater than 0, can not thereafter perform any write operation on a socket

2 (SHUT_RDWR): socket connected to the reading and writing are closed

Function return value

Success: 0

Failed: -1 failure reason stored in the error

 

(8) read function prototype

                read (read data from the open socket file stream)

 

 

The required header files

#include <unistd.h>

Function Description

Read data from the open socket stream file, only described the case where this function is applied to the socket

Function prototype

ssize_t read(int fd, void *buf ,size_t count)

Function parameter passing

fd: socket file descriptor

count: Maximum number of bytes read

Outgoing function parameters

buf: first address to read data

Function return value

Success: The actual number of bytes read

Failed: -1, the error code stored in the error

Additional information

Function call to read data read from the socket stream file, the following situations:

① socket receive buffer receiving data, returns the number of bytes received

② TCP protocol data received FIN, returns 0

③ TCP RST is received protocol data, returns -1 errno set ECONNRESET

Process ④ BLOCKING received signal returns -1 errno set to EINTR

 

(9) write function prototypes

                 write (data is written to the file stream socket)

 

 

The required header files

#include <unistd.h>

Function Description

Writing data to the socket file stream, this function is described here only applies to the case of the socket

Function prototype

ssize_t write (int fd,const void *buf,size_t count)

Function parameter passing

 

fd: socket file descriptor

buf: the first address of write data

count: Maximum number of bytes written

Function return value

Success: the number of bytes actually written

Failed: -1, the error code stored in the error

Additional information

When you call a function to write data to a socket write stream file, the following situations:

① bytes socket send buffer has enough space, the return transmission

② TCP RST is received protocol data, returns -1 errno set ECONNRESET

Process ③ BLOCKING received signal returns -1 errno set to EINTR

2. Senior socket function
recv and send functions provide read and write and similar functions. However, they provide a fourth parameter to control read and write operations.

(1) send function prototype

send (transmit data to each other through the socket file descriptor)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Send data to each other through the socket file descriptor

Function prototype

ssize_t send(int s, const void *buf, size_t len, int flags)

Incoming function value

s

socket file descriptor

buf

First address to send data

only

The length of the transmission data

flags

0: At this point function with write, flags can also be set to a combination of the following flags

MSG_OOB: band data transmission

MSG_DONTROUTE: Tell IP protocol, the destination host in the local network, it is not necessary routing table

MSG_DONTWAIT: Sets the nonblocking operation

MSG_NOSIGNAL: shows the transmission operation would not be interrupted SIGPIPE signal

Function return value

Success: the number of bytes actually sent

Failed: -1 failure reason stored in the error

 

(2) recv function prototype

recv (receive data from each other through the socket file descriptor)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Receive data from each other through the socket file descriptor

Function prototype

ssize_t recv(int s, void *buf, size_t len, int flags)

Incoming function value

s

socket file descriptor

only

The maximum data length receivable

flags

0: At this point function with read, flags can also be set to a combination of the following flags

MSG_OOB: receiving band data

MSG_PEEK: View data flag, the returned data is not deleted in the system, if you call recv function again will return the same data content

MSG_DONTWAIT: Sets the nonblocking operation

MSG_WAITALL: Forced received data before returning len size, unless an error signal is generated or

Outgoing value function

buf

First address to receive data

Function return value

Success: the number of bytes actually sent

Failed: -1 failure reason stored in the error

3. Socket function control property
system provides getsockopt, setsockopt two functions retrieve and modify some properties socket structure, by modifying these properties can be adjusted performance socket, thereby adjusting the performance of the application.

(1) getsockopt function prototype

getsockopt (to get a socket attributes)

The required header files

#include <sys/types.h>   

#include <sys/socket.h>

Function Description

Gets sockets property

Function prototype

int getsockopt(int s, int level, int optname,

                      void *optval, socklen_t *optlen)

Incoming function value

s

socket file descriptor

level

SOL_SOCKET: Universal socket option

IPPROTO_IP: IP Options

IPPROTO_TCP: TCP Options

optname

Option name to access, detailed in Table 18-3

optlen

The length optval

Outgoing value function

optval

The value of the acquired property

Function return value

Success: 0

Failed: -1 failure reason stored in the error

 

Table 18-3 socket attribute table

level (level)

optname (Option name

Explanation

type of data

SOL_SOCKET

 

SO_BROADCAST

Allowed to transmit broadcast data

int

SO_DEBUG

Allow debugging

int

SO_DONTROUTE

Without searching the routing

int

SO_ERROR

Get socket error

int

SO_KEEPALIVE

Stay connected

int

SO_LINGER

Close the connection delay

struct linger

SO_OOBINLINE

Band data into the normal data stream

int

SO_RCVBUF

Receive Buffer Size

int

SO_SNDBUF

Send Buffer Size

int

SO_RCVLOWAT

The lower limit of the receiving buffer

int

SO_SNDLOWAT

Send buffer limit

int

SO_RCVTIMEO

Receive Timeout

struct timeval

SO_SNDTIMEO

Send Timeout

struct timeval

SO_REUSERADDR

Allow reuse of local addresses and ports

int

SO_TYPE

Get the socket type

int

SO_BSDCOMPAT

Compatible with BSD systems

int

IPPROTO_IP

 

IP_HDRINCL

Included in the IP packet header

int

IP_OPTINOS

IP header options

int

IP_TOS

Service type

int

IP_TTL

Survival time

int

IPPRO_TCP

TCP_MAXSEG

The size of the largest segment of TCP data

int

CP_NODELAY

Nagle algorithm is not used

int

 

(2) setsockopt function prototype

setsockopt (socket set properties)

The required header files

#include <sys/types.h>   

#include <sys/socket.h>

Function Description

Set socket of property

Function prototype

int setsockopt(int s, int level, int optname,

                      const void *optval, socklen_t optlen)

Incoming function value

s

socket file descriptor

level

SOL_SOCKET: Universal socket option

IPPROTO_IP: IP Options

IPPROTO_TCP: TCP Options

optname

Option name settings, see Table 18-3

optval

Property values ​​set

optlen

The length optval

Function return value

Success: 0

Failed: -1 failure reason stored in the error

 

(3) getsockopt, setsockopt function example

sockopt.c source code is as follows:

#include <stdio.h>

#include <sys/types.h>

#include <sys/socket.h>

int main ()

{

    int sockfd,optval,optlen = sizeof(int);

    int sndbuf = 0 ;

    int rcvbuf = 0 ;

    int flag;

    if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)

    {

        perror("socket") ;

        return -1 ;

    }

    getsockopt(sockfd,SOL_SOCKET,SO_TYPE,&optval,&optlen);

    printf("optval = %d\n",optval);

    optlen = sizeof(sndbuf);

    flag = getsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&sndbuf,&optlen);

    printf("sndbuf=%d\n",sndbuf) ;

    printf("flag=%d\n",flag) ;

    sndBuf = 51200;   

    flag = setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&sndbuf, optlen);

    sndBuf = 0;

    flag = getsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&sndbuf,&optlen);

    printf("sndbuf=%d\n",sndbuf) ;

    printf("flag=%d\n",flag) ;

    close(sockfd);

    return 0 ;

}

Compile gcc sockopt.c -o sockopt.

Execution ./sockopt, execution results are as follows:

optval = 1

sndBuf = 16384

flag=0

sndBuf = 102400

flag=0

4. UDP read and write functions
UDP socket is a connectionless protocol, the data must be sent using the sendto function must use the recvfrom function to receive data, sending the destination address to be specified. sendto function to send basically the same function, and recv recvfrom function basically the same, but functions sendto and recvfrom function parameters in all address information with each other, these two functions is provided solely for the UDP protocol.

(1) sendto function prototype

sendto (transmit data to each other through the socket file descriptor)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Send data to each other through the socket file descriptors for the UDP protocol

Function prototype

ssize_t sendto(int s, const void *buf, size_t len, int flags,

                      const struct sockaddr *to, socklen_t tolen)

Incoming function value

s

socket file descriptor

buf

First address to send data

only

The length of the transmission data

flags

0: default way to send data, flags can also be set to a combination of the following flags

MSG_OOB: band data transmission

MSG_DONTROUTE: Tell IP protocol, the destination host in the local network, it is not necessary routing table

MSG_DONTWAIT: Sets the nonblocking operation

MSG_NOSIGNAL: shows the transmission operation would not be interrupted SIGPIPE signal

to

Storage destination host IP address and port information

tolen

to the length can be set to sizeof (struct sockaddr)

Function return value

Success: the number of bytes actually sent

Failed: -1 failure reason stored in the error

 

(2) recvfrom function

recv (receive data from each other through the socket file descriptor)

The required header files

#include <sys/types.h>

#include <sys/socket.h>

Function Description

Receive data from each other through the socket file descriptors for the UDP protocol

Function prototype

ssize_t recvfrom(int s, void *buf, size_t len, int flags,

                        struct sockaddr *from, socklen_t *fromlen)

Incoming function value

s

socket file descriptor

only

The maximum data length receivable

flags

0: data receiving default, flags may also be set to a combination of the following flags

MSG_OOB: receiving band data

MSG_PEEK: View data flag, the returned data is not deleted in the system, if you call recv function again will return the same data content

MSG_DONTWAIT: Sets the nonblocking operation

MSG_WAITALL: Forced received data before returning len size, unless an error signal is generated or

fromlen

From the length can be set to sizeof (struct sockaddr)

Outgoing value function

buf

First address to receive data

from

IP address and port storage sender

Function return value

Success: the number of bytes actually sent

Failed: -1, stored in the error cause of failure in
--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/10947712.html