Linux C Note Network programming (II)

Source: Internet
Author: User

Sockets

The struct SOCKADDR structure defines a common socket address, which he defines in Linux/socket.h as follows
struct SOCKADDR
{
unsigned short sa_family; The Protocol cluster address type of the socket, the TCP/IP protocol for IPV4 address type af_inet
Char sa_data[14];//stores the specific protocol address
};

Now generally use the following sockaddr_in structure (used to set/get address information):
struct SOCKADDR_IN
{
unsigned short sin_len; IPv4 Address length
short int sin_family; refers to the protocol cluster, which can be programmed in TCP sockets only Af_inet
unsigned short sin_port; Storage port number (using network byte order), data type is a 16 unsigned shaping type
struct IN_ADDR sin_addr;//Storage IP address, IP address is a in_add struct (structure below)
unsigned char sin_zero[8]; Empty bytes reserved for sockaddr and sockaddr_in two data structures to remain the same size
};
Among them, in_addr this data structure:
struct SOCKADDR_IN sock;
Unsistruct sockaddr_in Mysock;
sock.sin_family = af_inet; TCP Address Structure
Sock.sin_port = htons (80); Set the port number to 80
SOCK.SIN_ADDR.S_ADDR = inet_addr ("202.205.3.195"); Set IP Address
memset (sock.sin_zero, 0, sizeof (Sock.sin_zero)); Zeroing the array Sin_zero


The prototype of the Memset function is
memset (void * s, int c, size_t N);

A Creating sockets
#include <sys/types.h>
#include <sys/socket.h>
int socket (int domain, int type, int protocol);

Domain: Specifies the protocol family used to create the socket, as defined in header file <linux/socket.h>. Sometimes the pf_inet is used in the program, and the values of af_inet and pf_inet are consistent in the header file.
The common protocol families are as follows:
Af_unix: Create a socket that communicates only within this computer.
Af_inet: Using the IPV4TCP/IP protocol
AF_INET6: Using the IPV6 TCP/IP protocol
Note: Af_unix can only be used for single UNIX system interprocess communication, while Af_inet is for interne, allowing communication between remote hosts. It is generally assigned to af_inet.
Type: Indicates the types of socket communication, the corresponding parameters are as follows
Sock_stream: Creating a TCP stream socket
Sock_dgram: Creating a UDP datagram socket
Sock_raw: Creating the original socket
Protocol: Specifies the specific type of a protocol
The parameter protocol is typically set to 0, indicating that the protocol used is determined by the type of socket specified by the parameter domain specified by the protocol family and parameter type. When the original socket is not uniquely determined by the system, it is necessary to use that parameter to specify the protocol used.

Return value: Returns a newly created socket after successful execution, and returns a-1 if an error occurs, and the error code is stored in errno.


Create a TCP socket with code below
int sock_fd;
SOCK_FD = socket (af_inet, sock_stream, 0);
if (SOCK_FD < 0) {
Perror ("socket");
Exit (1);
}
The socket that created the UDP protocol is
SOCK_FD = socket (af_inet, SOCK_DGRAM, 0);

Two Establish a connection
The function connect is used to create a connection on a specified socket, the function prototype
#include <sys/types.h>
#include <sys/socket.h>
int connect (int socket, const struct SOCKADDR *serv_addr, socket_t Addrlen);

SOCK_FD: The socket file descriptor that is returned when the socket is established, called by the socket ().
SERV_ADDR: is a pointer to the data structure sockaddr, which includes the destination IP address and port number of the server to which the client needs to connect.
Addrlen: Indicates the size of the second parameter, you can use sizeof (struct sockaddr)

After successful execution, return 0, error occurs, return-1, error code is stored in errno.

Typically a socket that faces a connection (such as a TCP socket) can call the Connect function only once, whereas a disconnected socket (UDP socket) may call the Connect function multiple times to change the binding to the destination address
After the client has established the socket, it can directly connect to the server without the need for an address binding. The function that connects to the server is connect (), which connects the server that specifies the parameter, such as the IP address and port number.
In the case of TCP programming, the Connect () function is used by the server to make a connection request, and the server's IP address and port number are specified by the parameter serv_addr.
In the case of UDP programming, the Connect function does not establish a real connection, it simply tells the kernel the destination address (specified by the second parameter) that communicates with the socket, and only the data sent by that destination address is received by that socket. The benefit of calling the Connect function is that you do not have to specify the destination address each time you send and receive data.

The common usage of this function is as follows
struct sockaddr_in serv_addr;
memset (&serv_addr, 0, sizeof (struct sockaddr_in)); Serv_addr each word Chingqing 0
Serv_addr.sin_family =af_inet;
Serv_addr.sin_port = htons (80); Htons is a byte-order conversion function,
The Inet_aton function converts a string to a network address and assigns the address of the network to the second parameter
if (Inet_aton ("172.17.242.131", &serv_addr.sin_addr) < 0) {
Perror ("Inet_ation");
Exit (1);
}
Use the SOCK_FD socket to connect to the address specified by SERV_ADDR, assuming SOCK_FD is defined
if (Connect (sock_fd, (struct sockaddr *) &serv_addr, sizeof (struct sockaddr_in)) <0) {
Perror ("Connect");
Exit (1);
}

Note serv_addr coercion type to struct sockaddr type

Three Binding sockets
The function of bind () is to bind a socket file descriptor to an address and a port.
The function bind is used to bind a socket to a port, and the function's prototype
#include <sys/types.h>
#include <sys/socket.h>
int bind (int sockfd, struct sockaddr *my_addr, socklen_t Addrlen);

SOCKFD:SOCKFD is the file descriptor returned by the call to the socket function;
Addrlen is the length of the SOCKADDR structure.
MY_ADDR: is a pointer to the SOCKADDR structure that holds the address (that is, port and IP address) information for the local socket.
Returned: Successfully returned 0, failure returned-1.

Common methods of this function
struct sockaddr_in serv_addr;
memset (&serv_addr, 0, sizeof (struct sockaddr_in));
serv_addr.sin_family = AF_INEF;
Serv_addr.sin_port = htons (80);
SERV_ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);

if (Bind (SOCK_FD), (struct sockaddr *) &serv_addr, sizeof (struct sockaddr_in) < 0) {
Perror ("bind");
Exit (1);
}

Four Listening on sockets
The function listen converts the socket into passive listening, listen in the socket function to indicate that a socket is in the state of the incoming connection request, the function prototype
#include <sys/socket.h>
int listen (int s, int backlog);
No error, return 0,
Otherwise, the socket error is returned, and the function WSAGetLastError can be called to get the error code.

The Listen function uses an active connection socket to become a connected socket interface, which allows a process to accept requests from other processes, thereby becoming a server process. In TCP server programming, the Listen function transforms a process into a server and specifies that the corresponding socket becomes a passive connection.
The listen function is generally called after bind is called-before the accept call.
Common uses of this function
#define LISTEN_NUM 12//Define connection request Queue Length
....
if (Listen (SOCK_FD, Listen_num) < 0) {
Perror ("Listen");
Exit (1);
}


Five Accept Connection
The function accept is used to receive a connection request, the function prototype
#include <sys/types.h>
#include <sys/socket.h>
int accept (int s, struct sockaddr *addr, socklen_t *addrlen);
Parameters
S: A listener socket created by a function socket, bound to a port on a local end by a function bind, and then transformed by a function listen.
Addr: The address and Port of the host that is used to hold the originating connection request
Addrlen: Is the size of the struct that the addr points to

Execute successfully returns a new socket on behalf of the client, error 1, error code in errno, detailed with error code manual reference man manual

Return value: The return value of the Accept () function is the client socket file descriptor for the new connection, and communication with the client is done through the new socket file descriptor that is returned by the accept (), rather than by the file descriptor when the socket was established. If the accept () function has an error, accept () returns 1, and the error value can be obtained by errno.

If the socket specified by the parameter sock_fd is set to block mode (the default mode under Linux) and the connection request queue is empty, the accept () will be blocked until a connection request ends, and if the socket specified by the parameter S is set to nonblocking, if the queue is empty, Accept will return immediately -1,errno is set to Eagain.

A common method for this function in the case of a blocking socket
int client_fd;
int Client_len;
struct sockaddr_in client_addr;
...
Client_len = sizeof (struct sockaddr_in);
CLIENT_FD = Accept (sock_fd, (struct sockaddr *) &client_addr, &client_len);
if (CONN_FD < 0) {
Perror ("Accpt");
Exit (1);
}



Linux C Note Network programming (II)

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.