Socket programming 3: common functions in Socket network programming

Source: Internet
Author: User

This section was intended to give a common function introduction first, and then give two code instances, with the words saying that the discovery is getting longer and longer, and decided to put the code in the next section.

The content of this section is continuously updated ......

1 socket () function

Prototype:

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

Description:

Similar to opening a file, a socket descriptor is returned, which uniquely identifies a socket, and the subsequent operations use this socket descriptor.

Parameters:

Domain: protocol family. Common protocol families include af_inet, af_inet6, af_local, and af_route;

The protocol family determines the socket address type. The corresponding address must be used in communication. For example, af_inet determines that IPv4 and 16-bit port numbers should be used in the column;

Af_local decides to use an absolute path name as the address.

Type: socket type. Common socket types include sock_stream, sock_dgram, sock_raw, and sock_packet;

The socket type determines the transmission protocol to be used. For example, sock_stream corresponds to TCP and sock_dgram corresponds to UDP.

Protocol: Protocol, commonly used: ipproto_tcp, ipptoto_udp, ipptoto_sctp, etc;

They correspond to TCP, UDP, and sctp respectively.

Return Value:

A socket descriptor is returned successfully, and-1 is returned if the request fails.


2 BIND () function

Prototype:

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

Description:

Bind the socket to an address, including the IP address and port number.

Parameters:

Sockfd: A unique descriptor returned through socket;

ADDR: the address to bind to sockfd. It is a struct pointer. The struct address varies depending on the socket address family. The IPv4 address corresponds:

struct sockaddr_in {    sa_family_t    sin_family; /* address family: AF_INET */    in_port_t      sin_port;   /* port in network byte order */    struct in_addr sin_addr;   /* internet address */};/* Internet address. */struct in_addr {    uint32_t       s_addr;     /* address in network byte order */};
Addrlen: length of the corresponding address, obtained through sizeof

Return Value:

0 is returned for success, and-1 is returned for failure.


3 listen () function

Prototype:

int listen(int sockfd, int backlog);

Description:

Keep the socket in the listening status

Parameters:

Sockfd: the socket descriptor to be set to the listening status

Backlog: Maximum number of connections that can be queued

Return Value:

0 is returned for success, and-1 is returned for failure.

4 accept () function

Prototype:

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

Description:

Receive request

Parameters:

Sockfd: Listener socket descriptor of the server

ADDR: the URL of the requester.

Addrlen: Address Length

Return Value:

A new socket descriptor is returned successfully, and-1 is returned if the request fails.


5. Function for sending and receiving messages

Read ()/write (); Recv ()/send (); readv ()/writev (); recvmsg ()/sendmsg ();/* Recommended */recvfrom () /sendto ();

Prototype:

 #include <unistd.h>ssize_t read(int fd, void *buf, size_t count);ssize_t write(int fd, const void *buf, size_t count);#include <sys/types.h>#include <sys/socket.h>ssize_t send(int sockfd, const void *buf, size_t len, int flags);ssize_t recv(int sockfd, void *buf, size_t len, int flags);ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,             const struct sockaddr *dest_addr, socklen_t addrlen);ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,             struct sockaddr *src_addr, socklen_t *addrlen);ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);

Description:

The READ function can read content from the socket descriptor.

The Write function can write the content in the socket descriptor.

Parameter type:

Sockfd: Socket Descriptor

Buf/MSG: Data Stream

Len/count: Data Length

Flags: Call execution method, usually set to 0

Dest_addr: Destination Address

Src_addr: Source Address


Return Value:

When the corresponding function is successfully read, the number of actually read bytes is returned. When the function ends, 0 is returned. if the error is returned, the number is less than 0.

When the corresponding function is successfully written, the number of actually written bytes is returned, and-1 is returned if the function fails.


6. Close Function

Prototype:

int close(int fd);

Description:

Disable socket

Parameters:

FD: The socketfd or file FD to be closed

Return Value:

0 is returned for success and-1 is returned for failure.


7 perror

Prototype:

void perror(const char *s);

Description:

Output the cause of the previous function error to stderr. The parameter S is printed first, followed by the error cause string. The error string is determined by the value of the global variable errno.

There is an errno variable in the library function, and each value corresponds to the cause of the error represented in a string. When an error occurs when a function is called, the function resets the errno value.

Parameters:

The string before the error message.


8-byte sequence Conversion Function

There are two concepts:

Nbo: Network byte order network byte order, from the high to the bottom order from the storage (large-end priority ).

HBO: Host byte order the host's byte order, which varies with the CPU and therefore needs to be converted to nbo.

#include <netinet/in.h>uint16_t htons(uint16_t host16bitvalue);/*host to network Short init*/uint32_t htonl(uint32_t host32bitvalue);/* host to network long init */uint16_t ntohs(uint16_t net16bitvalue);/*network to host Short init*/uint32_t ntohl(uint32_t net32bitvalue); /*network to host long init*/  

9 address conversion functions

# Include <ARPA/inet. h> int inet_aton (const char * strptr, struct in_addr * addrptr);/* parameter 1: <span style = "font-family: Arial, Helvetica, sans-serif; font-size: 12px; "> string IP address; parameter 2: sin_addr in the address struct; </span> <span style =" font-size: 12px; font-family: Arial, helvetica, sans-serif; "> return value: 1 -- string IP valid, 0 -- </span> <span style =" font-size: 12px; font-family: Arial, helvetica, sans-serif; "> string IP address </span> <span style =" font-size: 12px; font-family: Arial, Helvetica, sans-serif; "> Error */</span> char * inet_ntoa (struct in_addr inaddr);/* convert a vertex into a string */in_addr_t inet_addr (const char * strptr ); /* convert the string IP address to the IPv4 address in the network byte order */
# Include <netinet/in. h> # define inet_addrstrlen 16 # define inet6_addrstrlen 46 # include <ARPA/inet. h> int inet_ton (INT family, const char * strptr, void * addrptr);/* return: 1 -- successful. The input is not in a valid expression format, -1 -- Error */const char * inet_ntop (INT family, const void * addrptr, char * strptr, size_t Len);/* return: pointer to result -- success, null -- Error */

The next group is a new function that can process IPv4 and IPv6.


10 setsockopt

Prototype:

int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);

Description:

During server-side development, this problem often occurs: the program can be started for the first time, and an error has been reported since the port is occupied, causing the program to fail.

The reason is that the port bound to the program is not released after the previous exit of the program. Therefore, you need to use this function to set the socket status.

Parameters:

Sockfd: Socket Descriptor

Level: defines the level. It supports sol_socket (General socket), ipproto_tcp (TCP socket), ipproto_ip (IPv4), and ipproto_ipv6 (IPv6)

Optname: select a name

Optval: option value, which is a pointer type pointing to a variable: integer, socket struct, other types of linger {}, timeval {}

Optlen: Option Length

Return Value:

0 is returned for success, and-1 is returned for failure.

Optname-detailed explanation of selection Name:

Option Name Description Data Type
========================================================== ======================================
Sol_socket
------------------------------------------------------------------------
So_broadcast allows sending broadcast data int
So_debug allows int debugging
So_dontroute
So_error get socket error int
So_keepalive
So_linger delay disconnection struct linger
So_oobinline put out-of-band data into normal data stream int
So_rcvbuf receive buffer size int
So_sndbuf sending buffer size int
So_rcvlowat lower limit int of the receiving buffer
So_sndlowat lower limit int of the sending Buffer
So_rcvtimeo receiving timeout struct timeval
So_sndtimeo sending timeout struct timeval
So_reuseraddr allows reuse of the local address and port int
So_type: Obtain the socket type Int.
So_bsdcompat is compatible with the BSD system int
========================================================== ======================================
Ipproto_ip
------------------------------------------------------------------------
Ip_hdrincl contains the IP header int in the data package.
Ip_optinos IP header option int
Ip_tos service type
Ip_ttl time int
========================================================== ======================================
Ippro_tcp
------------------------------------------------------------------------
Tcp_maxseg maximum TCP Data Segment Size int
Tcp_nodelay does not use the Nagle algorithm int
========================================================== ======================================

# Corresponds to a function: int getsockopt (INT sock, int level, int optname, void * optval, socklen_t * optlen );





Continuous updates ....................

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.