Linux/unix Socket Connection

Source: Internet
Author: User

Socket connections

A socket is a communication machine. By virtue of such a mechanism. The development of the customer/server system can be done on a local machine. Can also boast the network.

There is a difference between the creation and use of sockets and pipelines. Because the socket clearly separates the client from the server.

Socket connections:

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

Next. The server process gives the socket a name. The name of the local socket is the name of the file in the Linux file system, and for a network socket its name is the service identifier of the particular network to which the client is connected. This identifier agrees that Linux will go into the connection for a particular port number to the correct server process.

We use bind to name the socket. The server process then starts waiting for the client to connect to the named socket.

The function of the system call listen is. Create a queue and use it to hold incoming connections from customers. The server accepts the client's connection through the system call 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.

The client based on the socket system is simpler.

The customer first calls the socket to create an unnamed socket, and then calls the server's named socket as an address to connect with the server.

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 is capable of defining the format using one or more addresses.

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. It uses a specific way to specify the computers in the network, the IP addresses that people often say.

There may be multiple services executing at the same time on the server computer.

Customers can specify a specific service on a networked machine via Ipport. Inside the system, the port is identified by assigning a unique 16-bit integer, which, outside the system, needs to be determined by the combination of the IP address and port number.

Socket as the end point of the communication. A port must be bound before the communication begins.

Sockets fields can also be 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.

The socket for the Af_unix domain does not have this 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 ensures that it is not lost, copied, or ordered to arrive, and that 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. So they are very fast too. UDP represents the datagram protocol.

Socket protocol

Only the underlying transport mechanism is agreeing to more than one protocol to provide the required socket type. You can select a specific protocol for the socket.

Creating sockets

The socket system invokes the creation of a socket and returns a descriptive descriptor. The descriptive descriptor can be used to interview 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, and the type parameter specifies the kind of communication for this socket. 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. The latter is used for network sockets.

The type value contains 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 descriptive descriptor.

Socket address

Each socket field has its own format.

For Af_unix domain sockets. 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 the specified 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 includes 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 determined entirely 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 a ipport.

#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 description 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 for the incoming connection to be accepted 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 is able to wait for the client to establish a connection to the socket through the accept system call.

The Accept system call only returns when 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 a descriptive 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 will be placed in the SOCKADDR structure that is pointed to in the address parameter.

Parameter Address_len Specifies the length of the customer structure. Assuming that 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.

Assuming that 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 description descriptor, using the function Fcntl.

Request Connection

The customer connects to the server through a method that establishes 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);

SOCKFD the specified socket will be connected to the addr specified server socket, addr the length of the structure pointed to is specified by the number of references Addrlen.

Close socket

The ability to use the close function to terminate the connection of server and client sockets.

Host byte order and network byte order

In order for the different computers to be able to agree on the value of the multibyte integer transmitted over the network, a network byte order is required.

Customers and servers must convert their internal integer representations to network byte order before they are transferred.

The ability to complete this work through 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);

Transferring data

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);

The ability to use the above functions to set and get socket options.

Linux/unix Socket Connection

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.