Linux/unix Socket Connection

Source: Internet
Author: User

Socket connections

Socket is a communication machine, with this mechanism, the client/server system development work can be carried out on the local stand-alone, can also boast network. The creation and use of sockets differs from the pipeline because the sockets explicitly differentiate between the client and the server.

Socket connections:

First, the server application uses the system to invoke the socket to create a socket, which is a resource of a similar file descriptor that the system assigns to the server process, and it cannot be shared with other processes.

Next, the server process will give the socket a name. The name of the local socket is the file name in the Linux file system, and the name of the network socket is the service identifier associated with the specific network that the client is connected to. This identifier allows Linux to go to the correct server process for a connection to a specific port number. We use bind to name the socket. The server process then begins to wait for the client to connect to the named socket. The function of system call listen is to create a queue and use it to hold incoming connections from customers. The server accepts the client's connection through a system call to accept.

When the server calls accept, it creates a new socket that is different from the original named socket. This socket is used only to communicate with this particular customer, while the named socket is retained to continue processing the connection from the customer.

A client based on a socket system is simpler. The customer first calls the socket to create an unnamed socket, and then calls connect with the server as an address to establish a connection to the servers.

Socket properties

The properties of a socket are determined by three properties: domain, type, and protocol. The socket also uses the address as its name. The format of the address varies depending on the domain. Each protocol can also use one or more addresses to define the format.

Sockets for Fields

The domain specifies the network media used in socket communication. The most common socket field is af_inet, which refers to the internetwork. Its underlying protocol, the Internet Protocol, has only one address family, and it uses a specific way to specify the computers in the network, the IP addresses that people often say.

There may be multiple services running on the server computer at the same time. Customers can specify a specific service on a networked machine via an IP port. Inside the system, the port is identified by assigning a unique 16-bit integer, which, outside the system, needs to be determined by a combination of IP address and port number. The socket is the endpoint of the communication, and a port must be bound before the communication begins.

A socket field can also be a af_unix, even if a socket on a computer that is not networked can use the domain. The underlying protocol of this domain is the file input/output, and his address is the file name of the absolute path. The address of our server socket is server_socket.

Socket type

A socket field may have many different modes of communication, each of which has different characteristics. Af_unix domain sockets do not have such a problem because they provide a reliable two-way communication path.

Internet Protocol offers two different services: streaming and datagram

Stream sockets:

A stream socket provides an ordered, reliable, bidirectional byte stream connection. As a result, the data sent can be guaranteed not to be lost, copied, or ordered to arrive, and errors that occur during this process are not displayed. Flow sockets are specified by type Sock_stream, and they are implemented through TCP/IP connections in the af_inet domain. They are also the most common socket types in the Af_unix domain.

Datagram sockets

The datagram socket specified by type SOCK_DGRAM does not establish and maintain a connection. It has a limit on the length of datagrams that can be sent. Datagrams are transmitted as a separate network message and may be lost, copied, or ordered to arrive in a random order.

Datagram sockets are implemented through UDP/IP connections in the af_inet domain, providing an unreliable service that is not required. But from a Ziyun point of view, they are less expensive because there is no need to maintain network connectivity. And because it doesn't take time to build, they are fast. UDP represents the datagram protocol.

Socket protocol

As long as the underlying transport mechanism allows more than one protocol to provide the required socket type, you can select a specific protocol for the socket.

Creating sockets

The socket system call creates a socket and returns a descriptor that can be used to access the socket.

#include <sys/types.h>

#include <sys/socket.h>

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

The socket created is an endpoint of a communication line. The domain parameter specifies the protocol family, the type parameter specifies the kind of communication for this socket, and the protocol parameter specifies the protocol used.

The most common sockets are Af_unix and af_inet. The former is used to implement a local set of rings for UNIX file systems, which are used for network sockets.

The type values include Sock_stream and Sock_dgram.

The protocol used for communication is generally determined by the socket type and socket field, and usually does not require a selection. Setting the protocol parameter to 0 means using the default protocol.

The socket system call returns a descriptor.

Socket address

Each socket field has its own format.

For a Af_unix domain socket, its address is described by the structure sockaddr_un, which is defined in the header file Sys/un.h.

structsockrrd_un{

sa_family_t sun_family;

Char sun_path[];

};

Here sun_family specifies the address type, Sun_path specifies the socket address for the file name.

In the af_inet domain, the socket address is specified by the struct socketaddr_in, which is defined in the file Netinet/in.h and contains at least the following members:

structsocket_in{

short int sin_family;

unsigned short int sin_port;

struct IN_ADDR sin_addr;

};

The IP address structure in_addr is defined as

struct in_addr{

unigned long int s_addr;

};

The four bytes in the IP address constitute a 32-bit value, and a af_inet socket is fully determined by its domain, IP address, and port number.

Named sockets

For a socket created through a socket call to be used by another process, the server must name the socket. In this way, the Af_unix socket is associated with the pathname of a file system. Af_inet socket settlement is associated to an IP port.

#include <sys/types.h>/* See notes*/

#include <sys/socket.h>

int bind (INTSOCKFD, const struct SOCKADDR *addr, socklen_t Addrlen);

The BIND system call assigns the address in the parameter addr to the unnamed socket associated with the file descriptor socket. The length of the address structure is passed by the parameter Address_len.

Bind calls need to convert a specific address structure pointer to a common ground type (struct sockaddr *).

The BIND call successfully returned 0, and the failure returned-1.

Create a socket queue

In order to be able to accept incoming connections on the socket, the server program must create a queue to hold the unhandled request. This is done using the Listen system call.

#include <sys/types.h>/* See notes*/

#include <sys/socket.h>

int listen (int sockfd, int backlog);

In the socket queue, the number of incoming connections waiting to be processed cannot exceed the backlog. The subsequent connection will be rejected.

Accept Connection

#include <sys/types.h>/* See NOTES * *

#include <sys/socket.h>

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

Once the server program has created and named the socket, it can wait for the client to establish a connection to the socket through the accept system call.

The Accept system call is returned only if the client tries to connect to the socket specified by the SOCKFD parameter. The customer here refers to the first unhandled connection that is queued in the socket queue. The Accept function creates a new socket to communicate with the customer and returns the descriptor for the new socket. The type of the new socket is the same as the server listener socket type.

The socket must be named in advance by the bind call, and there is a listen call to assign him a connection queue. The address of the connecting customer is placed in the SOCKADDR structure pointed to by the address parameter.

The parameter Address_len specifies the length of the customer structure. If the length of the customer address exceeds this value, it will be truncated. So before calling accept, the Address_len must be set to the expected address length. When this call returns, Address_len will be set to the actual length of the connection client address structure.

If there are no unhandled junctions in the socket queue, the accept will be blocked until a client has established a connection. You can change this behavior by setting the O_NOBLOCK flag on the socket file descriptor, using the function Fcntl.

Request Connection

The customer connects to the server through a method of establishing a connection between unnamed sockets and the server listener socket.

#include <sys/types.h>

#include <sys/socket.h>

int Connect (INTSOCKFD, const struct SOCKADDR *addr, socklen_t Addrlen);

Parameter SOCKFD specifies that the socket is connected to the specified server socket for the parameter addr, addr the length of the structure pointed to is specified by the parameter Addrlen.

Close socket

You can use the Close function to terminate the connection between the server and the client socket.

Host byte order and network byte order

In order to agree on the value of multibyte integers that can be transmitted over the network by different computers, a network byte order is required. Customers and servers must convert their internal integer representations to network byte order before they are transferred. You can do this with the following functions.

#include <arpa/inet.h>

uint32_t htonl (uint32_t hostlong);

Uint16_thtons (uint16_t hostshort);

Uint32_tntohl (uint32_t netlong);

Uint16_tntohs (uint16_t netshort);

Htonl means "host tonetwork, Long".

Network Information

By calling Gethostent, you can find the host information for a given computer

#include <netdb.h>

Struct hostent *gethostent (void);

Void sethostent (int stayopen);

void endhostent (void);

Struct hostent{

Char *h_name;

Char **h_aliases;

Inth_addrtype;

Inth_length;

Char **h_addr_list;};

Get the network name and network number from the interface:

#include <netdb.h.

Struct netent * GETNETBYADDR (uint32_t net,int type);

Struct netent * getnetbyname (const char *name);

Struct netent * getnetent (void);

Void setnetent (int stayopen);

void endnetent (void);

Struct netent{

Char *n_name;

Char **n_aliases;

Intn_addrtype;

uint32_t n_net;};

The Protocol name and protocol number are mapped using the following function

#include <netdb.h>

Struct protoent * Getprotobyname (const char* name);

Struct protoent * Getprotobynumber (Intproto);

Struct protoent * getprotoent (void);

Void setprotoent (int stayopen);

void endprotoent (void);

Struct protoent{

Char *p_name;

Char **p_aliases;

Intp_proto;};

Mapping from a service name to a port number, the service name

#include <netdb.h>

Struct servent * getservbyname (const char *name, const char * proto);

Struct servent * getservbyport (int port,const char * proto);

Struct servent * getservent (void);

Void setervent (int stayopen);

void endservent (void);

Struct servent{

Char *s_name;

Char **s_aliases;

Ints_port;

Char *s_proto;};

Map from a host name and service name to an address

#include <sys/socket.h>

#include <netdb.h>

Int getaddrinfo (const char * restrict host,const char * Restrict service, const struct ADDRINFO * Restrict hint, Structad Drinfo * * Restrict res);

Void freeaddrinfo (struct addrinfo * ai);

Struct addrinfo{

Intai_flags;

intai_family;

Intai_socktype;

Intai_protocol;

Socklen_t Ai_addrlen;

STRUCTSOCKADDR * AI_ADDR;

Char *ai_canonname;

Structaddrinfo * AI_NEXT;};

Gai_strerror to convert the returned error code to an error message

#include <netdb.h>

Const char * gai_strerror (int error);

Convert address to host or service name

#include <sys/socket.h>

#include <netdb.h>

Int getnameinfo (const struct sockaddr *restrict addr, socklen_t Alen, char * restrict host,socklen_t Hostlen, char *restr ICT service, socklen_t servlen, unsigned int flags);

Data transmission

Send data:

#include <sys/types.h>

#include <sys/socket.h>

ssize_t Send (int sockfd, const 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 sendmsg (int sockfd, const struct MSGHDR *msg, int flags);

struct MSGHDR {

void *msg_name; /* Optional Address */

Socklen_t Msg_namelen; /* Size of Address */

struct Iovec *msg_iov; /* Scatter/gather Array */

size_t Msg_iovlen; /* # elements in Msg_iov */

void *msg_control; /* Ancillary data, see below */

size_t Msg_controllen; /* Ancillary DataBuffer len */

int msg_flags; /*flags on received message * *

};

Receive data:

#include <sys/types.h>

#include <sys/socket.h>

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

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

struct sockaddr *src_addr,socklen_t *addrlen);

ssize_t recvmsg (int sockfd, struct MSGHDR *msg, int flags);

Socket options

#include <sys/types.h>/* See notes*/

#include <sys/socket.h>

int getsockopt (int sockfd, int level, int optname,

void *optval, Socklen_t*optlen);

int setsockopt (int sockfd, int level, int optname,

const void *optval,socklen_t Optlen);

You can use the above functions to set and get socket options.

Related Article

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.