Introduction to Linux Sockets basics

Source: Internet
Author: User
Tags htons

The Linux socket library was ported from the BSD Unix system developed by Berkeley University. The BSD socket interface is a widely supported TCP/IP communication interface in many UNIX systems, and the socket programming under Linux is suitable for most other UNIX systems in addition to the small differences.

the socket interface is an API for TCP/IP networks, and the socket interface defines many functions or routines that programmers can use to develop applications on TCP/IP networks. the network socket data transmission is a special i/o,socket is also a kind of file descriptor .

The use of sockets is similar to file operations. Like the file read, write, open, close, and so on, TCP/IP network communication also has these operations, but it uses an interface that is not a file descriptor or file*, but a descriptor called a socket. Similar to file operations, for sockets, read, write, open, and close operations for network data transfer. At the same time, there are some auxiliary functions, such as domain name/IP address query, socket function settings and so on.

There are three types of sockets: Streaming sockets, datagram sockets, and raw sockets.

The flow socket defines a reliable connection-oriented service, which realizes the sequential data transmission without error or repetition. Datagram sockets define a non-connected service that transmits data through separate messages, is unordered, and is not guaranteed to be reliable and error-free. The original socket allows direct access to underlying protocols such as IP or ICMP, primarily for testing of new network protocol implementations.

the socket works as follows: The server starts first, establishes a socket by calling the socket (), and then calls Bind () to associate the socket with the local network address, and then calls Listen () Make the socket ready to listen and specify the length of its request queue, and then call accept () to receive the connection. After a socket is established, the customer can call connect () and the server to establish a connection. Once a connection is established, the client and server can send and receive data by calling read () and write (). Finally, when the data transfer is complete, both sides call Close () to turn off the socket.

Socket function Library:

1. Socket (int domain, int type,int protocol): This function assigns a socket handle that specifies the specific network under which communication is made using a specific protocol and data transfer method. After the socket handle is assigned, you need to establish a connection if you want to start TCP traffic. Depending on your needs, you can actively establish a connection (via connect ()) and passively wait for the other to establish a connection (via listen ()), before the connection is established to use read-write operations to exchange data over a network connection.

Domain parameters Select the protocol family used in communication, that is, the type of network, which can be one of the following: (1), Af_unix:unix Internal Protocol, (2), af_inet:arpa Internet Protocol, which is the TCP/IP protocol family, (3), af_ Iso:iso Agreement, (4), Af_ns:xerox Network Systems Agreement, (5), Af_implink:imp "host at IMP" link layer.

The type parameter is the way data is transferred, which can be one of the following: (1), Sock_stream: guaranteed sequential, reliable transmission of two-way byte data stream, the most common, is also used by TCP connections, (2), Sock_dgram: No connected, not guaranteed reliable, fixed length ( (3), Sock_seqpacket: sequential, reliable bidirectional fixed-length datagram transmission, only for af_ns types of networks, (4), Sock_raw: Raw data transfer, suitable for internal system-specific network protocols and interfaces, and Sock_ RDM, can only be used by super users, (5), SOCK_RDM: Reliable datagram delivery, not implemented.

The protocol parameter specifies the protocol used in the communication. After a given socket's protocol family and routing type, the protocol used in general is fixed, and the protocol parameter can use the default value of "0". However, if you have more than one protocol to choose from, you must use the protocol parameter to identify it.

The socket () function, which returns the socket descriptor when normal execution occurs, otherwise returns 1, and the error state is in the global variable errno.

2. Close (int fd): The socket and file descriptor are closed using this function. The FD parameter is the socket descriptor. The return value, which normally returns 0,-1, indicates an error.

3. bind (int sockfd, structsockaddr *my_addr, int addrlen): This function specifies the local address for the socket that is already open. The use of this function has the following two cases: (1), if the socket is connection-oriented, and this socket in the connection establishment process in a passive position, that is, the party B program uses the Listen function to wait for the other party to establish a connection, the other side with the Connect function to establish a connection to this socket , in this case, you must use bind to set the local address for this socket. When party B uses the Listen function, in addition to specifying the socket descriptor, the socket must already have the local address (including the IP address and port number) set with the BIND function, so that the system receives the network request to make the connection, depending on the destination address of the request. Identify the connection to which socket, so that party B can receive the packet that is sent to this socket address. This socket cannot be used for connection establishment and data reception without specifying the local address of the socket. (2), if the socket is used for a non-connected situation, also requires that the socket set local address, so that after the system receives data from the network, it will know which socket and its corresponding process.

SOCKFD parameter: Used to specify the socket descriptor.

Addrlen parameter: The length of the MY_ADDR structure.

MY_ADDR parameter: The local address used to listen for connection requests. struct SOCKADDR is a versatile structure that includes not only the TCP/IP protocol, but also other networks, such as Af_ns. Because of its versatility, it simply defines a storage space in a general sense.

The BIND function returns a value of 0 when it is normal, otherwise returns 1, while errno is the system error code.

4. Listen (int s, int backlog): Ready to receive connection requests. After setting the local address to a socket with bind (), the socket can be used to receive the connection request, i.e. listen (). After calling listen (), the system will provide the socket with a connection request queue, the staging system receives the request to establish a connection to this socket, waiting for the user program to formally receive the request with accept (). The queue length, as specified by the backlog parameter. If a short period of time to establish a connection to party B too many requests, party B too late to deal with, then the backlog after the request will be rejected by the system. Therefore, the backlog parameter actually stipulates that the party B program can allow the connection to establish processing speed. As for the party B program using this socket (and its designated local address) actually establish the number of connections, by the party B program call accept () the number of times to decide.

Listen function return value: Returns 0 if normal, otherwise returns-1.

5. Accept (int s, struct sockaddr*addr, int *addrlen): Accepts connection requests on the specified socket. After calling listen (), the system stores each connection request to the socket (and its local address) in the connection request staging queue of the socket. The action of the Accept () function is to take a connection request from the staging queue, create a new socket:socket_new with the data of the Socket, and assign it a file descriptor. Socket_new identifies the established connection, which can be used by party B to take place and receive data (Write/read, SEND/RECV) to the other side of the connection. At the same time, the original socket remains open and continues to wait for network connection requests.

If there is no pending connection request in the socket's staging queue, blocking is blocked based on the socket's feature option (non_blocking), and the Accept () function chooses two ways: if the socket is not non_ Blocking, accept () waits until a connection request is received, and if the socket is of type non_blocking, then accept () returns immediately, but if there is no connection request, only the error message is returned and no new socket is created _new. After the Accept () is returned, if a new socket_new is created to identify the newly established connection, then the parameter addr the specified structure will have the address information of the other party, Addrlen is the length of the address information.

S parameter: Socket descriptor.

Addr parameter: Accept () stores the address information of the other party in the structure that the addr points to after accepting the connection. If it is a af_inet Socket, the address information is the local IP address and port number.

Addrlen parameter: Before calling accept (), the *addrlen must be set to the legal length of the addr data structure. After the Accept () is returned, the *addrlen is the length of the opposite address information.

Accept function return value: If a new connection is created normally, a non-negative integer is returned, that is, the new connection's socket descriptor (note that the original socket used to wait for the connection request remains open and can be used to receive new connection requests), otherwise, 1 is returned.

bind, listen, connect and other functions are used to passively wait for each other to establish a connection, while the Connect function is used when the connection is actively established . Connect () uses a pre-opened socket, and the destination party (that is, the communication partner, or the server party) address information, to the other side to make a connection to establish a request.

6. Connect (int sockfd, structsockaddr *serv_addr, int addrlen): The client sends a service request.

SOCKFD parameter: The socket descriptor returned by the socket function.

SERV_ADDR: A structure that stores the IP address and port information for a remote computer.

Addrlen: Is the length of the structural body sockaddr_in.

Return value: Successfully returns 0, otherwise returns-1.

7. Send (int s, const void *msg,int len, unsigned int flags)/sendto (int s, const void *msg, int len, unsignedint fla GS, const struct SOCKADDR *to, int tolen), recv (int s, void*buf, int len, unsigned iint flags)/recvfrom (int s, void *buf, I NT len,unsigned int flags, struct sockaddr *from, int *fromlen): sends and receives data with the socket. After the connection is established, both parties can use these functions to send and receive data. Where send and recv are used for connection establishment after the sending and receiving. SendTo and recvfrom are used for non-connected protocols. For non-non_blocking type socket,send will wait for the data to be sent after the return, for the non_blocking type of socket,send will return immediately, the user program needs to use the Select () function to determine whether the network sends the end. Similarly, for a non-non_blocking socket, if the system does not receive any data, recv will wait for the incoming data to arrive before returning, and for the non_blocking type SOCKET,RECV will return immediately and return an error message or the number of bytes of data received. SendTo and Recvfrom because of the non-connected send and receive, you must give the destination address in the parameters or the space to store the source address.

S parameter: Socket descriptor.

MSG,BUF parameter: Store storage space for receiving or sending data.

Len parameter: The number of bytes to receive or send data.

To,from parameters: The destination party address and the space where the source address is stored by sendto and recvfrom.

Tolen,fromlen parameter: The destination address and the source address space size.

Flag parameter: Usually set to 0.

Return value: Send/sendto returns the actual number of bytes of data sent, or 1, indicating an error. Recv/recvfrom returns the number of data bytes actually received, or-1, indicating an error.

8. Read (int fd, void *buf, Size_tcount)/write (int fd, const void *buf, size_t count): Socket communication with System file operation. After the connection is established, for the passive party during connection establishment, after the normal return of accept (), it returns a new socket and assigns a file descriptor to the socket, and for the connection request initiator, connect () returns after normal return. The corresponding socket also contains the assigned file descriptor. Therefore, you can use the standard UNIX file read-write function read ()/write () for socket communication. It is important to note that because the network data and disk files are not the same, it is not ready, so each read and write operation may not be able to pass the specified length of data, need to be repeated by the program of the rest of the transfer. In addition, the file descriptor is the lower-level file manipulation function, which differs from the commonly used file* in C language. File* is a read-write operation using the Fread/fwrite function.

FD parameter: file or socket descriptor.

BUF parameter: Data buffer.

Count parameter: Number of data bytes.

function return value: When normal, returns the number of bytes read and written (note that it may be less than the number specified by the count parameter); otherwise, 1.

9. getsockopt (int s, int level,int optname, void *optval, int *optlen)/setsockopt (int s, int level, intoptname, con st void *optval, int optlen): Gets, sets the socket feature option.

several commonly used conversion functions: (1), inet_addr: Convert the IP address from the point format to an unsigned long integer, the address it returns is the network byte format, (2), Inet_ntoa: Output a IN_ADDR structure into the number format ; (3), htonl: Translates 32-bit host byte order into 32-bit network byte order, (4), htons: translates 16-bit host byte order into 16-bit network byte order, (5), Ntohs: Converts an unsigned short shape number from network byte order to host byte order; (6 ), Ntohl: Converts an unsigned long shape number from the network host order to the host byte order.

Here are the test cases:

1. Client.cpp:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include < netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include < arpa/inet.h> #include <iostream> #define PORT 7000int Main () {struct sockaddr_in server;int s, Ns;int Pktlen, Buflen;char buf1[256], buf2[256];s = socket (af_inet, sock_stream, 0); server.sin_family = Af_inet;server.sin_port = htons (PORT); server.sin_addr.s_addr = Htons (Inaddr_any); if (Connect (s, (struct sockaddr*) &server, sizeof (server)) < 0 {perror ("Connect ()"); return-1;} for (;;) {printf ("Enter a Line:"); Std::cin>>buf1;buflen = strlen (BUF1); if (Buflen = = 1) break;send (S, buf1, buflen+1, 0); rec V (S, buf2, sizeof (BUF2), 0);p rintf ("Received line:%s\n", buf2);} Close (s); return 0;}
2. Server.cpp:

#include <stdio.h> #include <string.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #define PORT 7000int Main () {struct sockaddr_in client, Server;int s, ns, Pktlen;char buf[256];s = socket (af_inet, sock_stream, 0); memset ((Char *) &server, sizeof (server), 0); server.sin_family = Af_inet;server.sin_port = htons (port); server.sin_addr.s_addr = Htons (Inaddr_any); Bind (S, (struct sockaddr*) &server, sizeof (server)); Listen (S, 1); socklen_t Namelen = sizeof ( client); ns = accept (s, struct sockaddr*) &client, &namelen); for (;;) {Pktlen = recv (ns, buf, sizeof (BUF), 0), if (Pktlen = = 0) break;printf ("Received line:%s\n", buf); for (int i = 0; i < str Len (BUF); i++) Buf[i] = ToUpper (buf[i]); Send (NS, buf, Pktlen, 0);} Close (NS); close (s); return 0;}

Implementation instructions: (1), open the terminal, respectively, execute: $ g++-O server server.cpp, $ g++-O client client.cpp; (2), open the terminal, first execute the server-side program: $./server; then open another terminal, execute the client program: $./client, (3), program function: The server receives data from the client and converts the data it receives to uppercase and then sends it to the client. The client displays the resulting data after it is received. Exits when a character length is entered.

The above sections are organized from the network.



Introduction to Linux Sockets basics

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.