Basic function of socket

Source: Internet
Author: User
Tags error code function prototype unix domain socket port number htons
Basic operation of Socket:
(1) socket () function:
(2) Bind () function:
(3) Listen (), connect () function;
(4) The Accept () function;
(5) The Send and receive functions in the socket:
(6) The Close () function:
(7) The socket function is called on the server:
(8) The client calls the socket function:
(9) IP address conversion function: Inet_pton, Inet_ntop, inet_addr:
--------------------------------------
(1) socket () function:


1) function prototype:
int socket (int domain, int type, int protocol);
2) Analysis:
The socket function corresponds to the open operation of the normal file. The open operation of a normal file returns a file descriptor, and the socket () is used to create a socket descriptor (socket descriptor), which uniquely identifies a socket. The socket descriptor is the same as the file descriptor, and subsequent operations are useful to it, using it as a parameter to perform some read and write operations.
Just as you can give fopen a different parameter value to open a different file. When creating a socket, you can also specify different parameters to create different socket descriptors.


3) Parameters:
1.domain: The protocol domain, also known as the Protocol Family (family):


Common protocol families are af_inet, Af_inet6, af_local (or Af_unix,unix domain sockets).
Used to differentiate between creating a IPv4 socket (af_inet) or IPv6 socket (AF_INET6).


Af_unix, indicating that the socket is neither a IPv4 socket nor a IPv6 socket, but a non-network UNIX domain socket that can be used for non-network inter-process communication (inter-process communication).
----
2.type: Specify socket Type:
Commonly used socket types are, Sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket and so on.
1.sock_stream This protocol is a sequential, reliable, data-complete byte-stream-based connection. This is the most used socket type, which is transmitted using TCP.
2.sock_dgram This protocol is a non-connected, fixed-length transfer call. The protocol is unreliable and uses UDP to connect to it.
3.sock_raw This socket type provides a single network access, this socket type uses the ICMP public protocol. (Ping, traceroute Use this Protocol)
---
3.protocol: public agreement;
Common common protocols are ipproto_tcp, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, and so on, which correspond to TCP transport protocol, UDP Transmission protocol, STCP transmission Protocol and TIPC Transmission protocol respectively.


Note: The above type and protocol can not be arbitrarily combined, such as sock_stream can not be combined with IPPROTO_UDP. When protocol is 0 o'clock, the default protocol corresponding to type types is automatically selected.


4) return value:
Returns the socket description word that identifies the socket. The return value exists in the Protocol family (address family,af_xxx) space, but does not have a specific address. If you want to assign an address to it, you must call the bind () function, or the system will automatically randomly allocate a port when you call Connect (), listen ().


--------------------
(2) Bind () function:
1) Function:
Bind a specific IP address, port port number to the socket;
The bind () function assigns a specific address in the address family to the socket. If the corresponding af_inet, Af_inet6 is a IPv4 or IPv6 address and port number combination assigned to the socket.
Associate the socket with a port on your local computer (often you need to call this function when designing a server-side program.) You can then listen to the service request on that port, and the client typically does not need to call the function.


2) Prototypes:
int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);


3) Parameters:
1.SOCKFD: That is, the socket description:
It is created through the socket () function and uniquely identifies a socket.


Addr: A const struct SOCKADDR * Pointer to the protocol address to bind to SOCKFD, containing information about your address: name, port, and IP address. This address structure differs depending on the address protocol family at the time the socket was created.


As IPv4 corresponds to:
struct SOCKADDR_IN {
sa_family_t sin_family; /* Address family:af_inet */
in_port_t Sin_port; /* port in Network byte order */
struct IN_ADDR sin_addr; /* Internet address */
Usually set the setting Sin_addr to Inaddr_any (means arbitrary)
};


/* Internet address. */
There is only one unique field in the/*sin_addr struct s_addr, which represents the IP address, which is an integer that is generally used by the function inet_addr () to convert an IP address in the form of a string into a unsigned long integer value and then to S_ADDR. */
struct IN_ADDR {
uint32_t s_addr; /* address in network byte order */
};


You can use the following assignment to automatically get the native IP address and randomly get a port number that is not occupied:
My_addr.sin_port = 0; /* The system randomly selects an unused port number */
MY_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; /* Fill in the native IP address */


Attention:
1. The service program can put htonl (inaddr_any) to s_addr when the IP address is bound to its socket, and the benefit is that the client program can communicate with the service program regardless of the network segment;
2. If you only bind a fixed IP address to the socket that is running the service program on the host, only the client program that is on the same network segment as the IP address can communicate with the service program.


----
IPv6 corresponds to:
struct SOCKADDR_IN6 {
sa_family_t sin6_family; /* AF_INET6 */
in_port_t Sin6_port; /* Port number */
uint32_t Sin6_flowinfo; /* IPV6 Flow information */
struct IN6_ADDR sin6_addr; /* IPV6 Address */
uint32_t sin6_scope_id; /* Scope ID (New in 2.4) */
};


struct IN6_ADDR {
unsigned char s6_addr[16]; /* IPV6 Address */
};


----
The UNIX domain corresponds to the following:
#define UNIX_PATH_MAX 108


struct Sockaddr_un {
sa_family_t sun_family; /* Af_unix */
Char Sun_path[unix_path_max]; /* Pathname */
};


3) Addrlen: corresponds to the length of the address.


4) Normally the server will bind a well-known address (such as IP address + port number) when it is started, so that the client can connect to the server through it to provide service.
The client does not have to specify that a system automatically assigns a port number and its own combination of IP addresses.
This is why the server usually calls bind () before listen, and the client does not invoke it, but instead generates one randomly from the system at Connect ().


5) return Value:
The bind () function returns 0 when it is successfully called, and it is also a flag that returns –1 as an error when the bind () function calls an error. The value of ERRN is the error code. All ports less than 1024 are reserved for use as a system port, and no root rights are available. You can use any port above 1024, up to 65535. A common error calling bind () is Eaddrinuse, where the specified address is in use, the specified port number is used, the IP address can be used by multiple processes, but the port can only be used by one process at a time.


6) Bind Example:
The following is an example of a bind function call:
struct sockaddr_in saddr;
memset (void *) &saddr,0,sizeof (SADDR));
saddr.sin_family = af_inet;
Saddr.sin_port = htons (8888);
SADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
SADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.22.5"); Binding fixed IP
Bind (Listensocket, (struct sockaddr *) &saddr,sizeof (SADDR));


------------
(b) Network byte order and host byte order:


(1) Host byte order:
The host byte order is what we normally call the big-endian and small-end patterns: Different CPUs have different byte-order types. These byte orders are the order in which integers are stored in memory, which is called the host order. The reference standard Big-endian and Little-endian are defined as follows:


A) The Little-endian is the low-bit bytes emitted at the lower address of the memory, high-bit bytes emitted in the memory of the higher address.
such as the 32-bit hexadecimal number 0x12345678 is stored in 4 bytes of memory: 78 is stored in the first byte, 56 is stored in the second byte, 34 is the third byte, and 12 is the fourth byte.


b) The Big-endian is the high-bit byte emitted at the low address of the memory, and the low byte is discharged at the upper address of the memory.
such as the 32-bit hexadecimal number 0x12345678 is stored in 4 bytes of memory: 12 is stored in the first byte, 34 is stored in the second byte, 56 is the third byte, and 78 is the fourth byte.


c) Big-endian small-end example diagram and its comparison:
1. Example diagram:


2. Comparison:
The use of big-endian data storage in line with human normal thinking, and the use of small-end method of data storage is conducive to computer processing.


(2) Network byte order:
http://blog.csdn.net/legend050709/article/details/39890997

(3) Note:
When binding an address to a socket, first convert the host byte order into a network byte order, instead of assuming that the host byte order is Big-endian with the network byte order. As a result of this problem has caused a massacre. Because of this problem in the company project code, it leads to a lot of puzzling problems, so remember not to make any assumptions about the host byte-order, so be sure to convert it into a network byte order and assign it to the socket.


(2.1) htonl ():


1) Prototypes:
unsigned long int htonl (unsigned long int hostlong);
2) Background:
There are two kinds of byte precedence for computer data storage: high byte precedence and low byte priority. Data on the Internet is transmitted over the network in high order byte precedence, so for machines that store data internally as a low-byte priority, a conversion is required to transfer data over the Internet.
Several byte order conversion functions:
Htons ()--"Host to Network short"; HTONL ()--"Host to Network Long"
Ntohs ()--"Network to Host short"; Ntohl ()--"Network to Host Long"
Here, h denotes "host", N means "network", s means "short", and L means "long".


------------
(3) Listen () function:
1) Prototypes:
int listen (int sockfd, int backlog);
2) Function:
Call Listen () to listen to the socket, and if the client calls connect () to make a connection request, the server will receive the request.
3) Parameters:
SOCKFD is a socket descriptor for the socket descriptor to listen on.
The maximum number of connections that the corresponding socket can queue for the backlog.
What does the backlog specifically mean? Each incoming request is entered into a queue of incoming requests, and the program that waits for listen calls the Accept () function, which is described below, to receive the connection. When the system has not yet called the Accept () function, if there are many connections, the maximum number of local waits can be the backlog value.


4) return value:
Listen () If –1 is returned, then an error occurred during the execution of listen ().


5) Note:
The socket created by the socket () function defaults to an active type, and the Listen function changes the socket to a passive type, waiting for the client's connection request.


--------------------
(3.1) Connect () function;


1) Prototypes:
int connect (int sockfd, struct sockaddr *serv_addr, int addrlen);
2) Parameters:
SOCKFD: Socket file descriptor, returned by the socket () function, which is the client's sockfd.
SERV_ADDR is a structure that stores the IP address and port information of a remote computer, typically the server's IP with port.
Addrlen should be sizeof (struct sockaddr).


3) Function:
The client establishes a connection to the TCP server by calling the Connect function.


-------------
(4) The Accept () function;
0) Procedure 1:
After the TCP server invokes the socket (), bind (), listen (), it listens for the specified socket address. The TCP client calls the socket (), connect () in turn, and then wants the TCP server to send a connection request. After the TCP server hears this request, it calls the Accept () function to take the receive request, so the connection is established. You can then start network I/O operations, which are similar to read/write I/O operations for normal files.


1.0) Procedure 2:
1. Someone tries to call Connect () from far and far away to connect to a port on your machine (of course you are already in listen).
2. His connection will be listen into the wait queue waiting for the call of the Accept () function (the maximum number of join waiting queues is determined by the second parameter backlog that calls the Listen () function).
3. You call the Accept () function and tell him that you are ready to connect.
The Accept function returns a new socket descriptor, which represents the connection.


1) Prototypes:
int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);
2) Parameters:
SOCKFD: The socket description word for the server;
Addr: Stores information about a computer that is connected remotely (such as the IP address and port of a remote computer). The protocol address used to return the client.
addrlen:sizeof (struct sockaddr_in)


3) return value:
If Accpet succeeds, then its return value is a completely new description Word generated automatically by the kernel, representing the TCP connection to the returned client.
4) Note:
The first parameter of the 1.accept is the server's socket descriptor, which is generated by the server starting to call the socket () function, called the listener socket descriptor.
The 2.accept function returns a connected socket descriptor.
3. A server typically creates only one listener descriptor, which persists throughout the lifetime of the server.
4. The kernel creates a connected socket descriptor for each client connection accepted by the server process, and when the server has completed a service to a customer, the corresponding connected socket descriptor is closed.


------------------
(5) The Send and receive functions in the socket:
http://blog.csdn.net/legend050709/article/details/39804275


------------------
(6) The Close () function:


1) Background:
Completion of the Read and write operation is to close the corresponding socket descriptor, such as the operation of the open file to call fclose close the open file.
2) Prototypes:
int close (int sockfd);


3) Function:
Sockets will not be allowed for read and write operations. Any operation that reads and writes to the socket descriptor will receive an error.


4) Shutdown ():
1. Prototypes:
#include <sys/socket.h>
int shutdown (int sockfd, int how);


2. Function:
Allows you to do a one-way shutdown or disable all.
3. Parameters:
SOCKFD: is a socket descriptor that you want to close.
How: You can take the following values:
0 indicates that subsequent data receive operations are not allowed;
1 indicates that subsequent data is not allowed to be sent;
2 means that no future operations (including receiving, sending data) are allowed, as with close ()




--------------
(7) The socket function is called on the server:
1) Order:
Socket () ———— bind () ———— listen () ———— accept ():


Call the socket () function to create a socket.
Call the bind () function to bind itself to an address.
Call the Listen () function to listen for the connection.
Call the Accept () function to accept all incoming requests.
Call the recv () function to get the information introduced and then call the Send () answer.


--------------
(8) The client calls the socket function:
Socket ()->connect ():


--------------------------------------------
(9) GetSockName function:
1) Prototypes:
int getsockname (int sockfd, struct sockaddr *name, socklen_t *namelen);
int getpeername (int sockfd, struct sockaddr *peeraddr, int *addrlen);
2) Function:
GetSockName: Return to local protocol address: Getpeername: Return remote Protocol Address


When no bind () or bind () is invoked without specifying a local protocol address, you can call GetSockName () to return the local IP address and port number that the kernel assigns to this connection, and to obtain the protocol family for a set of interfaces.
When a new connection is established, the server can also call GetSockName () to get the local IP address assigned to this connection.


When a child process of a server calls the Exec function to start execution, only the Getpeername () function can be called to obtain the client's IP address and port number.


3) Parameters:
SOCKFD: The socket that needs to get the name.
Name: The buffer that holds the name of the acquired socket.
Nemalen: As the entry parameter, name points to the maximum length of space.


4) Applicable situation:
The GetSockName () function is used to get the name of a set of interfaces. It is used for a bundled or connected set of interfaces s, and the local address will be returned. This call is especially useful when you call connect () without calling bind (), and only the getsockname () call can tell the local address of the system's default. On return, the Namelen parameter contains the actual number of bytes of the name.


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


(9.0) IP address conversion function: inet_addr:
1) Prototypes:
in_addr_t inet_addr (const char * strptr);
2) Function:
Converts the string IP address to the IPV4 address structure in_addr value.


--------------------------------------------
(9) IP address conversion function: Inet_pton:


1) function: [Dotted decimal, "integer"]:


The IP address is converted between dotted decimal and integer. And can be handled to handle IPv4 and IPv6.


2) Prototypes:
int Inet_pton (int af, const char *src, void *DST);


This function converts the string to the network address, the first parameter AF is the address family, and after the conversion exists in DST.


3) Description:
Inet_pton is an extension of inet_addr, and the supported multi-address families have the following:
AF = Af_inet
SRC is the address that points to the character type, the first address of the ASCII address (in DDD.DDD.DDD.DDD format), and the function converts the address into a IN_ADDR structure and replicates it in *DST.


AF = Af_inet6
SRC is the address that points to IPV6, and the function converts the address into a IN6_ADDR structure and replicates it in *DST.


4) return value:
If a function error returns a negative value and the errno is set to Eafnosupport, the function returns 0 if the address family specified by the parameter AF is not the same as the SRC format.




----------------------------------------------------------
(Ten) IP address conversion function: Inet_ntop
1) function: [Integer, Dotted decimal]


This function converts the network binary structure to the ASCII type address, the function of the parameter is the same as above, just one more parameter socklen_t cnt,
He is the point of the buffer DST size, avoid overflow, if the buffer is too small to store the value of the address, a null pointer is returned, and the errno is set to ENOSPC.
2) Prototypes:
const char *inet_ntop (int af, const void *SRC, char *dst, socklen_t CNT);




3) Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main (void)
{
Char ipdotdec[20]; Store dot decimal IP address
struct IN_ADDR s; IPV4 Address Structure Body
Enter IP address
printf ("Please input IP address:");
scanf ("%s", &ipdotdec);
Transformation
Inet_pton (Af_inet, Ipdotdec, (void *) &s);
printf ("inet_pton:0x%x\n", s.s_addr); Note the resulting byte order
Inverse conversion
Inet_ntop (Af_inet, (void *) &s, Ipdotdec, 16);
printf ("Inet_ntop:%s\n", Ipdotdec);
}





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.