Linux on TCP,UDP and broadcast and multicast Communications (Code encyclopedia) __linux

Source: Internet
Author: User
Tags data structures rfc sendmsg socket error terminates
Linux under TCP,UDP and broadcast and multicast Communications (Code encyclopedia)

TCP, UDP, broadcast, multicast client server code link addresses are (for free):

TCP Code: http://download.csdn.net/detail/huangminqiang201209/4860661
UDP Code: http://download.csdn.net/detail/huangminqiang201209/4860665
Broadcast code: http://download.csdn.net/detail/huangminqiang201209/4860672
Multicast code: http://download.csdn.net/detail/huangminqiang201209/4860719

Tcp

Transmission Control Protocol Transmission Control Protocol TCP is a connection-oriented, reliable, byte-throttling transport layer (Transport Layer) communication protocol, described by the IETF RFC 793 (specified). In the simplified computer network OSI model, it completes the function specified in layer Fourth transport layer, and UDP is another important transport protocol in the same layer.
In the Internet Protocol family (Internet protocol suite) Four layer protocol, the TCP layer is the transport layer above the IP layer, under the application layer. A reliable, pipe-like connection is often required between the application tiers of different hosts, but the IP layer does not provide such a flow mechanism, but rather provides an unreliable packet exchange.

 

Udp
UDP is the abbreviation of User Datagram protocol, the Chinese name is the Subscriber datagram Protocol, is a connectionless transport layer protocol in the OSI Reference Model, it provides a simple and unreliable information delivery service for transaction, and IETF RFC 768 is the formal specification of UDP.

Broadcasting

Broadcast and multicast are applied only to UDP, which is important for applications that need to transmit messages to multiple receivers simultaneously. TCP is a connection-oriented protocol, which means that there is a connection between two processes (determined by the port number) that are running on two hosts (determined by the IP address), respectively.
Consider shared channel networks, such as Ethernet, that contain multiple hosts. Each Ethernet frame contains the Ethernet address (bit) of the source host and destination host. Typically, each Ethernet frame is sent only to a single destination host, and the destination address indicates a single receive interface and is therefore called a unicast (unicast). In this way, the communication of any two hosts does not interfere with other hosts within the network, except where it may cause contention for shared channels. However, sometimes a host sends frames to all other hosts on the Web, which is broadcast. This process can be seen through ARP and RARP. Multicast (multicast) is between unicast and broadcast: frames are routed only to multiple hosts that belong to a multicast group.

Multicast

Multicast data is only received by an interface that is interested in the datagram, that is, the interface that is running on the host that wants to participate in the multicast session application system. Broadcasts are generally limited to local area networks, while multicast can be used for LAN or WAN.
IP multicast provides two types of services:
1 Transmit data to multiple destination addresses. There are many applications that transmit information to multiple receivers: An interactive conferencing system, for example, and distribution of messages or news to multiple receivers. If multicast is not used, most of these applications are now implemented by TCP (sending a separate data copy to each destination address). However, even with multicast, some applications may continue to adopt TCP to ensure its reliability.
2 client requests to the server. For example, diskless workstations need to be determined to boot the boot server. Currently, the service is broadcast, but using multicast can reduce the burden of not providing this service host.

Function

1.socket function
Specifies the desired communication protocol type.
#include <sys/types.h> * * NOTES */
#include <sys/socket.h>

int socket (int domain, int type, int protocol);
Returns: If the success is a nonnegative descriptor, the error is-1.

Parameter description:
Domain: Specifies that the protocol family, also known as the protocol domain, is a constant value.
Af_inet IPV4 Protocol
Af_inet6 IPV6 Protocol
Af_local/af_unix UNIX Protocol Domain
Af_route Routing sockets
Af_key key sockets

Type: Indicates the types of sockets.
Sock_stream byte throttle socket (TCP)
Sock_dgram datagram Sockets (UDP)
Sock_seqpacket ordered grouping sockets
Sock_raw Original Socket

Protocol: Specifies the protocol type. Typically 0 to select a system default value for the given domain and type combination.
IPPROTO_TCP TCP Transport Protocol
IPPROTO_UDP UDP Transport Protocol
IPPROTO_SCTP SCTP Transport Protocol
Function Description:
The socket function returns a small nonnegative integer value when it succeeds, similar to the file descriptor, which we call the socket descriptor, abbreviated SOCKFD. To get this socket descriptor, we just specified the protocol family (IPV4, IPV6
or Unix) and a socket type (byte stream, datagram, or original socket). We do not specify a local and remote protocol address.

2.bind function
Assigns a local protocol address to a socket. For the Internetwork Protocol, the Protocol address is a combination of a 32-bit IPV4 address and a 128-bit IPV6 address and a 16-bit TCP or UDP port number. The BIND function is used primarily on the server side to specify local
Which network interface of the host (IP, can be inaddr_any, represents any network interface of the local host) can accept the client's request and specify the port number (that is, the process that is open to wait for the client to connect).

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

Parameter description:
The socket descriptor returned by the Sockfd:socket function.
MYADDR, Addrlen: A pointer to a socket address structure and the size of the structure.

struct SOCKADDR structure description is as follows:
struct SOCKADDR_IN {
short int sin_family; /* Address Family * *
unsigned short int sin_port; /* Port Number * *
struct IN_ADDR sin_addr; /* IP Address * *
unsigned char sin_zero[8]; /* Fill 0 to keep the same size as struct sockaddr * *
};

Function Description:
For TCP, the BIND function can be invoked to specify a port number, or specify an IP address, either both specified, or both.
The server bundles their well-known port numbers at startup (how to bundle them). )。 If a TCP client or server has not invoked bind binding a port, the kernel will select a temporary port for the corresponding socket when calling connect or listen.
It is normal for the TCP client to have the kernel select a temporary port unless the application requires a reservation port. It is extremely rare for TCP servers, however, because servers are known through their well-known port numbers.

A process can bind a specific IP to its socket, but this IP address must belong to one of the network interfaces of its host (for a TCP server). For TCP clients, this assigns the source IP address (the server source address) to the IP datagram that is sent on the socket. For a TCP server, this qualifies the socket to receive only those client connections destined for this IP address. A TCP socket usually does not bind an IP address to its socket. When a socket is connected, the kernel chooses the source IP address based on the outgoing network interface used, and the outgoing port depends on the path required to reach the server. If the TCP server does not bind the IP address to its socket, the kernel will use the destination IP address of the sent SYN as the source IP address of the server (that is, the server IP equals Inaddr_any).
In fact, the client's source IP address is the server's destination address, the server's source IP address is the client's destination address, in the final analysis, there are only two IP addresses: client IP and server IP.

3.connec function
The T TCP client uses the Connect function to establish a connection to the TCP server.

#include <sys/socket.h>
int connect (int sockfd, const struct SOCKADDR *servaddr, socklen_t Addrlen);
Return: If the success is 0, the error is-1.

Parameter description:
SOCKFD: The socket descriptor returned by the socket function.
SERVADDR, Addrlen: A pointer to a socket address structure and the size of the structure. The socket address structure must contain the IP address and port number of the server.

Function Description:
The client does not have to call the BIND function before calling the Connect function, and if necessary, the kernel determines the source P address and selects a temporary port as the source port. So the sockets in the client process generally only need to indicate the IP and port number of the server to which the customer is connecting.
If it is a TCP socket, calling the Connect function will trigger the TCP's three-way handshake. and returns only if the connection succeeds or fails. There are several things that are wrong:
1-> TCP clients did not receive a response from the SYN section.
The response of the 2-> TCP server to the customer's SYN section is RST.
A 3-> client issued a SYN section where an error occurred on a router device.
If the connect call fails, the socket is no longer available and must be closed, and we cannot perform the Connect function again on such a socket.

4.listen function
#include <sys/socket.h>
int listen (int sockfd, int backlog);
Return: If the success is 0, the error is-1.

Function Description:
The Listen function is only invoked by the TCP server, and it does two things.
(1) Converts an disconnected socket (active) to a passive socket, indicating that the kernel should accept a connection request to that socket.
(2) The backlog parameter sets the maximum number of connections that the kernel should queue for the corresponding socket. Where the kernel always maintains two queues for listening sockets.
(1) The connection queue is not completed, and each SYN section is for one of the following:
A client has been issued and reached the server, and the server is waiting for the TCP three-way handshake process to be completed. These sockets are in a SYN_RCVD state.
(2) Completed connection queue
Each customer who has completed the TCP three-way handshake process corresponds to one of the items. These sockets are in a established state.
Backlog is the maximum value for both queues and.
After the three-way handshake completes, but the data that arrives before the server invokes accept should be queued by the TCP server, the maximum amount of data being the size of the receive buffer for the corresponding connected socket.

5.accept function
The Accept function is invoked by the TCP server to return the next completed connection from the completed connection queue header. If the completed queue is empty, the process is put into sleep (assuming the socket is the default blocking mode).
#include <sys/socket.h>
int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
Returns: If the success is a nonnegative connected descriptor and a pair of IP and port numbers, the error is-1.

Parameter description:
CLIADDR, Addrlen is used to return the protocol address of the connected End-to-end process (customer). Before the call, we set the integer value referenced by *addrlen to the length of the socket address structure referred to by CLIADDR, which is the exact number of bytes the kernel holds in the socket address mechanism.

Function Description:
If the accept call succeeds, its return value is a completely new descriptor generated automatically by the kernel, representing the TCP connection to the returned customer. When discussing the Accept function, we call its first parameter a listener socket descriptor (created by the socket and subsequently used as a descriptor for the first parameter of bind and listen), which is called the concatenated socket descriptor. It is important to distinguish between these two sockets. A server typically creates only a listening socket, which persists throughout the lifetime of the server. The kernel creates a connected socket for each client connection that is accepted by each server process (that is, the TCP three-way handshake process has been completed). When the server completes a service to a connected customer, the corresponding connected socket is closed.

6.recv/recvfrom function
Receives a message from a socket. For Recvfrom, both connection-oriented and connectionless sockets can be applied at the same time. Recv are generally used only in connection-oriented sockets, almost equivalent to Recvfrom, as long as the fifth parameter of Recvfrom is set to null. If the message is too large to be fully stored in the provided buffer, the extra bytes are discarded according to the different sockets. If there is no message on the socket to read, the receive call waits for the message to arrive, except that the socket has been set to non-blocking mode.

#include <sys/types.h>
#include <sys/socket.h>
ssize_t recv (int sock, void *buf, size_t len, int flags);
ssize_t recvfrom (int sock, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);

Parameters:
Sock: The socket from which the index will receive data.
BUF: Stores the buffer after the message is received.
Len:buf the capacity of the buffer to be referred to.
Flags: A combination of one or more of the following flags, which can be connected by an OR operation
Msg_dontwait: operation will not be blocked.
Msg_errqueue: Indicates that the error value should be received from the socket's error queue, and that the error value is passed in the form of some kind of auxiliary message, and that the user should provide a buffer that is large enough. The intact package that causes the error is passed as general data by Msg_iovec. The datagram that caused the error the original destination address is provided as a msg_name. The error is used in the SOCK_EXTENDED_ERR structure form, as defined below
#define So_ee_origin_none 0
#define SO_EE_ORIGIN_LOCAL 1
#define SO_EE_ORIGIN_ICMP 2
#define SO_EE_ORIGIN_ICMP6 3
struct SOCK_EXTENDED_ERR
{
u_int32_t Ee_errno; /* ERROR Number * *
u_int8_t Ee_origin; /* Where the error originated * *
u_int8_t Ee_type; /* Type * *
u_int8_t Ee_code; /* Code * *
u_int8_t Ee_pad;
u_int32_t Ee_info; /* Additional Information * *
u_int32_t Ee_data; /* Other Data * *
/* More data may follow * *
};

Msg_peek: Indicates that after the data is received, the original data is kept in the receive queue, not deleted, and subsequent reads can receive the same data.
Msg_trunc: Returns the actual length of the packet, even if it is longer than the supplied buffer and is valid only for packet sockets.
Msg_waitall: Blocking operations are required until the request is fully satisfied. However, if a signal is caught, an error or connection breaks development, or the next time the data type is received, the data that is less than the requested amount is returned.
Msg_eor: Indicates the end of the record, and the returned data completes a record.
Msg_trunc: Indicates that the datagram tail data has been discarded because it requires more space than the supplied buffer.
Msg_ctrunc: Indicates that some control data has been discarded due to insufficient buffer space.
Msg_oob: Indicates receipt of Out-of-band data (that is, data that requires priority processing).
Msg_errqueue: Indicates that no other data was received except for errors from the socket error queue.
From: Point to the area where the address is to be placed, and if NULL, do not store the End-to-end address.
Fromlen: As the entry parameter, point to the memory unit representing the from maximum capacity. As an exit parameter, point to the memory unit that represents the from actual length.

7.send/sendto function
Used to send messages. Send is only available for connection based sockets, and the only difference between send and write is the presence of the flag, which is equivalent to write when the flag is 0 o'clock. SendTo and sendmsg can be used both for connectionless sockets and for connections based sockets. Except that the socket is set to non-blocking mode, the call will block until the data is sent out.

#include <sys/types.h>
#include <sys/socket.h>
ssize_t Send (int sock, const void *buf, size_t len, int flags);
ssize_t sendto (int sock, const void *buf, size_t len, int flags, const struct SOCKADDR, *to socklen_t);
ssize_t sendmsg (int sock, const struct MSGHDR *msg, int flags);

Parameters:
Sock: The socket from which the index will send data.
BUF: A buffer that points to the data that will be sent.
Len: The length of the buffer above. Len can be greater than sizeof (BUF), such as Send ("123")--> actually send 10 bytes of data
Flags: A combination of the following 0 or more flags that can be connected by or operation
Msg_dontroute: Do not use gateways to send packets, only to direct-networked hosts. This flag is used primarily for diagnostics or routing programs.
Msg_dontwait: operation will not be blocked.
Msg_eor: Terminates a record.
Msg_more: The caller has more data to send.
Msg_nosignal: When the other end terminates the connection, the request does not send a sigpipe signal on a stream-based error socket.
Msg_oob: Send Out-of-band data (data that needs to be processed first), while existing protocols must support this operation.
To: Point to the area that holds the address of the receiving end, which can be null.
Tolen: The length of the above memory area can be 0.
Msg: A memory buffer that points to the header of the sending message, with the following structure form
struct MSGHDR {
void *msg_name;
Socklen_t Msg_namelen;
struct Iovec *msg_iov;
size_t Msg_iovlen;
void *msg_control;
Socklen_t Msg_controllen;
int msg_flags;
};
The data structures that may be used are
struct CMSGHDR {
Socklen_t Cmsg_len;
int cmsg_level;
int cmsg_type;
};

8.getsockname function
Gets the local name of a set of interfaces.
#include <sys/socket.h>
int getsockname (int sockfd, struct sockaddr *localaddr, socklen_t *addrlen);
Return: Success is not returned, error is 1.

Parameters:
SOCKFD: A descriptor that identifies an interface that has been bundled.
LOCALADDR: The address (first name) of the receiving set interface.
Addrlen: Name buffer length.

Function Description:
The GetSockName () function is used to get the name of a socket. It is used for a bundled or connected socket SOCKFD, and the local address is returned. This call is particularly useful when you invoke connect () without calling bind (), when only the getsockname () call can be informed of the local address of the system. When returned, the Namelen parameter contains the actual number of bytes of the name.
If a socket is bundled with a inaddr_any, which means that the socket can be addressed by any host, then getsockname () will not return any information about the host IP address unless it is called connect () or accept (). Windows socket applications should not assume that IP addresses will change from Inaddr_any to other addresses unless sockets are connected. This is because for multiple host environments, the IP address used by the socket is not known unless the socket is connected.

9.getpeername function function
Gets the end address that is connected to the sleeve interface.
int getpeername (int sockfd, struct sockaddr *peeraddr, socklen_t *addrlen);
Return: Success is not returned, error is 1.

Function Description:
The Getpeername () function is used to obtain the port name that is bundled with it from the port sockfd and to store it in the name structure of the sockaddr type. It applies to datagram or stream class socket interfaces.

10.setsockopt/getsockopt function
Set/Get Sleeve interface options
#include <winsock.h>
int setsockopt (int sockfd, int level, int optname, void *optval, int optlen);
int getsockopt (int sockfd, int level, int optname, void *optval, int *optlen);

Parameters:
S: Identifies a descriptive word for a set of interfaces.
Level: The hierarchy of option definitions; currently supports only sol_socket and ipproto_tcp levels.
Optname: Options you want to set.
Optval: Pointer to the buffer that holds the option value.
The length of the optlen:optval buffer.

Note:
        setsockopt () function is used for setting option values for any type, any state set interface. Although there are options on different protocol tiers, this function defines only the highest options on the "set interface" level. Options affect the operation of the socket interface, such as whether the expedited data is received in the normal data stream, whether the broadcast data can be sent from the socket, and so on.

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.