Network programming api-(Basic API)

Source: Internet
Author: User
Tags sendmsg htons

Htons, Ntohs, htonl, and Ntohl functions

Linux provides 4 functions to complete the conversion between host byte order and network byte order

#include <netinet/in.h>uint16_t htons (uint16_t host16bitvalue); uint32_t htonl (uint32_t host32bitvalue); uint16 _t Ntohs (uint16_t net16bitvalue); uint32_t Ntohl (uint32_t net32bitvalue);

Inet_aton, inet_addr, and INET_NTOA functions

#include <arpa/inet.h>int inet_aton (const char *strptr, struct in_addr *addrptr); Returns: 1 if the character is valid, otherwise 0in_addr_t inet_ Addr (const char *strptr); Returns: 32-bit binary network byte-order address if the string is valid, otherwise Inaddr_nonechar *inet_ntoa (struct in_addr inaddr); Return: Address that points to a dotted decimal number string

Inet_aton converts the string that strptr points to a 32 network byte-order binary value and stores it through ADDRPTR, successfully returning 1, and failing back to 0. INET_ADDR does the same conversion as Inet_aton, inet_addr cannot handle dotted decimal string 255.255.255.255 because its binary value is used only to fail the function return, but some compiler inaddr_none is not necessarily the case.

Note that the IN_ADDR structure of these 3 function operations is the network byte order. Network binary and dot-string conversions are best done with Inet_pton and inet_ntop functions, which are protocol independent.

Inet_pton and Inet_ntop functions

#include <arpa/inet.h>int inet_pton (int family, const char *strptr, void *addrptr); return: Success is 1, input is not a valid expression returns 0, Error -1const char *inet_ntop (int family, const void *addrptr, char *strptr, size_t len); return: Success is a pointer to the result, error is null

Both functions apply to both IPV4 and IPv6, and p represents the expression (presentation) and the value (numeric). The first function attempts to convert the string referred to by the StrPtr pointer, holding the binary result through the ADDPTR pointer, successfully returning 1 if the input is not a valid expression format for the specified family, then returns 0

Inet_ntop does the opposite, and if Len's value is too small to hold the expression result, a null pointer is returned and the error is ENOSPC

socket and connect functions

#include <sys/socket.h>int socket (int family, int type, int protocol), return: Non-negative descriptor returned successfully, error returned-1

The socket function specifies the desired type of communication protocol (such as TCP with IPV4, UDP with IPv6, UNIX domain Byte throttle protocol), and socket type (byte stream, datagram, or raw socket)

The family constant of the----socket function------------

Family description
Af_inet IPV4 Protocol
Af_inet6 IPV4 Protocol
Af_local UNIX Protocol domain
Af_route Routing sockets
Af_key secret key sockets
----------------------------------------------------

----The type constant of the socket function----------------

Sock_stream byte throttle socket

Sock_dgram datagram sockets

Sock_seqpacket ordered packet sockets

Sock_raw RAW sockets

----------------------------------------------------

The protocal constant of the----socket function----------

IPPROTO_CP TCP Transport Protocol

IPPROTO_UDP UDP Transport Protocol

IPPROTO_SCTP SCTP Transfer Protocol

----------------------------------------------------

#include <sys/socket.h>int connect (int sockfd, const struct sockaddr* servaddr, socklen_t Addrlen); return: Success is 0, error 1

tcp The customer uses the connect tcp server connection, sockfd is by socket The socket descriptor returned by the function, the second one, The third parameter is a pointer to a socket address structure and the size of the structure, which must contain the server's ip address and port number. If connect fails, you must close current socket descriptor and recall socket

Bind and Listen functions

#include <sys/socket.h>int bind (int sockfd, const struct SOCKADDR *myaddr, socklen_t Addrlen); return: Success is 0, error 1

The BIND function assigns a local protocol address to a socket, which simply assigns a protocol address to a socket, and the meaning of the protocol address depends on the protocol itself. The second parameter points to a pointer to the protocol address structure, the third parameter is the length of the protocol address, and for TCP, the BIND function can either specify a port number, specify an IP address, or both, or neither.

#include <sys/socket.h>int Listen (int sockfd, int backlog); return: Successful return 0, error 1

When a socket is created, it is assumed to be an active socket, that is, it is a client socket that will invoke connect to initiate a connection. The Listen function converts an unbound socket to a passive socket, indicating that the kernel should accept connection requests to that socket, and calling the Listen function will cause the socket to transition from Closee state to listen state. The second parameter specifies the maximum number of connections that the kernel should queue for the corresponding socket.

(1), the connection queue is not completed: Each such SYN sub-section corresponds to one of the following: A customer has been issued and reached the server, and the server is waiting to complete the corresponding TCP three-way handshake process. These sockets are in the SYN_RCVD state.

(2), completed connection queue: Each customer that completes the TCP three-way handshake process corresponds to one of these sockets, which is in the established state.


Accept function

#include <sys/socket.h>int Accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen); return: Successfully returns the connected descriptor (non-negative). ERROR-1

if Accept successful, then its return value is a new socket generated automatically by the kernel, representing the TCP connection, the first parameter of the function is a listening socket, and the return value is a connected socket

Server, client program flowchart

Server client Simple interactive program see: http://blog.csdn.net/u012796139/article/details/44984879


TCP state transition diagram


Recv and send functions

TCP stream data Read and write

#include <sys/socket.h>ssize recv (int sockfd, void *buff, size_t nbytes, int flags); ssize Send (int sockfd, void *buf F, size_t nbytes, int flags); return: number of bytes read or written successfully, error 1


Msg_oob for Send, which indicates that out-of-band data will be sent, only one byte on the TCP connection can be sent as out-of-band data, and for recv, this flag indicates that out-of-band data is about to be read instead of normal data.

Msg_peek This flag applies to recv and Recvfrom, which allows us to view the data that has been read, and discards it when the system is not returning recv and Recvfrom

Note that the flags parameter is valid only for the current invocation of send and recv, but can also permanently modify some of the socket's properties by setsockopt system calls

Recvfrom and SendTo functions

#include <sys/socket.h>ssize_t recvfrom (int sockfd, void *buf, size_t nbytes, int flags, struct sockaddr *from, sock Len_t *addrlen); ssize_t recvto (int sockfd, void *buf, size_t nbytes, int flags, struct sockaddr *to, socklen_t Addrlen); return : The number of bytes successfully read or written, with a failure of-1

The first 3 parameters sockfd, buf, and nbytes are equivalent to the 3 parameters of the Read and write functions: descriptors, pointers to read-in or write-out buffers, and read and write bytes

Recvmsg and SENDMSG functions

#include <sys/socket.h>ssize_t recvmsg (int sockfd, struct MSGHDR *msg, int flags); ssize_t sendmsg (int sockfd, Struc T MSGHDR *msg, int flags); return: Success is the number of bytes read or written out, error 1

The MSG parameter is a MSGHDR struct type pointer

struct msghdr{void *msg_name;//socket address socklen_t msg_namelen;//socket address length struct Iovec *msg_iov;//scattered memory block int iovlen;// Number of scattered memory blocks void *msg_control;//points to the starting address of the secondary data socklen_t msg_controllen;//the secondary data size int msg_flags;//The flags parameter in the copy function and updates it during the call; struct iovec{void *iov_base;//memory start address size_t iov_len;//this memory length}

The IOVEC structure encapsulates the starting address and length of a piece of memory, Msg_iovlen specifies how many of these iovec structures are, and for recvmsg, the data is read and placed in the Msg_iovlen block-separated memory, where and how long the memory is in the Msg_ Iov points to an array specified, which becomes decentralized read (scatter read); for Sendmsg, the Msg_iovlen block of scattered memory data is sent by a piece, which becomes a centralized write (gather write)

Msg_control and Msg_controllen are used to send auxiliary data.

The Msg_flags member does not need to be set, it replicates the contents of the RECVMSG/SENDMSG flags parameter to affect the data read and write process. Recvmsg also sets some of the updated flags to Msg_flags before the call ends. The flags parameter and the return value of the recvmsg/sendmsg all have the same meaning as the SEND/RECV's flags parameter return value.

getsockname and Getpeername functions

#include <sys/socket.h>int getsockname (int sockfd, struct sockaddr *localaddr, &addrlen); int getpeername (int SOCKFD, struct sockaddr *peeraddr, &addrlen); return: Success is 0, error 1
GetSockName gets the sockfd corresponding to the local socket address and stores it in the memory address specified by the address parameter, which is stored in the variable that the Addrlen points to. Getpeername gets the remote socket address.

Getsockope and setsockopt functions

#include <sys/socket.h>int getsockopt (int sockfd, int level, int optname, void *optval, socklen_t *optlen); int Setso ckopt (int sockfd, int level, int optname, void *optval, socklen_t optlen); return: Success is 0, error 1

SOCKFD points to an open socket descriptor, level specifies the code that interprets options in the system or is a generic socket code, or is a protocol-specific code such as IPV4, IPV6, TCP, or SCTP. Optval is a pointer to a variable (*optval), setsockopt from the size of the *optval has the last parameter specified, it is a value parameter for setsockopt, and for getsockopt is a value-result parameter.

Note:There are two types of socket options: one is to enable or disable the two-dollar option for an attribute (become a flag option), and the other is to obtain and return the options (called Value options) for the specific values we can set or check. The column labeled "Flag" indicates whether an option is a flag option, and when the getsockopt function is called for these flag options, *optval is an integer, and a return of 0 in *optval indicates that the option is disabled and no 0 indicates that the corresponding option is started. Similarly, setsockopt requires a *optval that is not 0 to start the option, and a *optval for 0 to disable the option. If "." is not in the flag, then the appropriate option is used to pass the value of the specified data type between the user process and the system.

SO_RCVBUF and SO_SNDBUF socket options

Each socket has a send buffer and a receive buffer, the receive buffer is used by TCP, UDP, and SCTP to hold the received data until it is read by the application process, and for TCP, the amount of space available in the socket receive buffer limits the size of the TCP advertisement window. The TCP socket buffer cannot overflow because the side is not allowed to emit more data than the window size, and this TCP will discard them. For UDP is no traffic control: the faster the sender can easily drown the slower receiver, resulting in the receiver UDP dropped data, in fact, the faster the sender can even drown the local network interface, causing the datagram to be discarded by the machine.

When you set TCP when a socket receives a buffer size, the order of the function calls is important because TCP window sizing options are used when establishing a connection SYN The sub-sections are exchanged with the peer. for the client, this means that the SO_RCVBUF option must be set before calling connect, and for the server, this means that the option must be set on the socket before calling listen. Setting this option on a connected socket has no effect on the possible window sizing options, because accept does not create and return a connected socket until the TCP three handshake is complete, which is why the option must be set for the listener socket. The socket buffer size is inherited from a listening socket by a newly created connected socket.

gethostbyname function

#include <netdb.h>struct hostent *gethostbyname (const char *hostname); return: Success is a non-null pointer, error is null and set H_errno

The function returns a non-null pointer structure with the following hostent structure

struct Hostent{char *h_name;char **h_aliases;int  h_addrtype;int  h_length; * * Length of address:4 */char **h_ Addr_list;}

According to DNS, GetHostByName is performing a-record query (DNS resource records have a, AAAA, PTR, MX, CNAME, etc.), it can only return IPV4 address, note that the function returns a struct HOSTENT * structure

gethostbyaddr function

#include <netdb.h>struct hostent *gethostbyaddr (const char *ADDR, socklen_t len, int fanily); return: Success is a non-null pointer, Error is null and collocated H_errno
The addr parameter is not a char * structure, but a pointer to the IN_ADDR structure that holds the IPV4 address, the Len parameter is the size of the structure, and the ipv4,family parameter is af_inet

Getservbyname and Getservbyport functions

#include <netdb.h>struct servent *getservbyneme (const char *servname, const char *protoname); struct servent * Getservbyport (int port, const char *protoname); return: Success is a non-null pointer, error NULL
The non-null pointer returned by the function points to the following structure:

struct Servent{char *s_name;char *s_aliases;/* alias list */int  S_port;char *s_proto;}
Mapping from first name to port number is typically stored in a file (usually/etc/services)
The Getservbyname parameter servname must be specified, and if Protoname is specified (as a non-null pointer), the specified service must match the protocol. If Protoname is not specified, and servname points to a service that supports multiple protocols, then returning that port number depends on the implementation, usually without a relationship, because multiple protocols with the same service generally have the same TCP and UDP port numbers, but this does not guarantee
The port parameter of the Getservbyport must be a network order
Usage examples:
struct servent *pserv;
Pserv = Getservbyname ("FTP", "TCP");
Pserv = Getservbyport (htons), "TCP");


Reference:

1, "UNIX Network Programming" 4th Chapter 11th Chapter

2, "Linux High Performance Server Programming" chapter 5th Linux network programming Basic API

3, server, client simple interactive program http://blog.csdn.net/u012796139/article/details/44984879

Network programming api-(Basic API)

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.