Network address data structure problems
First of all, first of all, the programming address in the network, I do not know if anyone find that in our network programming is not only a single address data structure, and many times we call the network interface when we have to cast the parameters of the type. Yes, I'm talking about the data structure sockaddr and sockaddr_in, and if you're careful enough, you'll find that most of the programming we use is sockaddr_in, but the network interfaces we call are almost all (don't know if it's not, I have to investigate) SOCKADDR type of, why? Let's take a look at the definitions of these two data structures as follows:
/** * General network address structure */struct sockaddr{ __uint8_tsa_len; /* Byte total length */ sa_family_tsa_family; /* [XSI] Address family */ charsa_data[14];/* [XSI] addr value (actually larger) */};/** * Socket addr ESS, Internet style. * We generally use the network address * This is the IP4 type, defined in the header file <netinet in= "" h= "" > * IP6 type has a corresponding data structure, cut the size and IP4 of different, here does not say */struct sockaddr_ in{ __uint8_tsin_len; sa_family_tsin_family; In_port_tsin_port; /* Byte Port */ structin_addr sin_addr; /* Byte IP address */ charsin_zero[8]; /* byte reserved field */};
From the definition of the above code and comments we can find that sockaddr is a generic address data structure, the last 14 bytes are reserved, and sockaddr_in is a structure using the back of the sockaddr_in, the size of two data structures, Just sockaddr_in defines some bytes that are not defined by SOCKADDR. I think this is because I want to let the system platform itself determine the use of the following 14 bytes, but also give a unified interface, the above implementation is XSI implementation of the version.
Therefore, we usually declare sockaddr_in such a type of address structure, and then initialize the result, and finally converted to sockaddr such a type of parameter into the function to use.
TCP network communication process
Server : The TCP server first needs to use the socket function to create a socket_server and then bind the initialized server address information to socket_server using the BIND function. After the binding succeeds, the server side uses listen to enter the listening state, then the server calls the Accept function to enter the state waiting for the client connection, when the program will block the call to Acept, until a client requests a connection, the program will continue to execute. At this point, the server side can communicate with the client using the socket_client returned by the function accept, and if the address parameter of the accept is not NULL, the address information of the client can also be obtained. You can use the read and write functions to communicate with clients, and when you need to end communication with the client, you can use close to close socket_client and disconnect the client. When the final program exits, don't forget to socket_server the previous listener socket to close.
Client : The client is simpler than the server side, there is no so-called listening and accepting connection requests, but there is a request Connection section, the following is how the client communicates with the server. First, the client uses the socket to create a communication socket, and then uses the server's address and port information to initialize the communication address structure, and then uses the successful socket and the initialized communication address information to request a connection to the server via the Connect function, if the connection is successful, You can then use the socket to communicate with the server, or you can use the read and write functions to get and send messages, and when communication is not required, the client calls close to close the socket and disconnects from the server.
In fact, there is a flowchart is very simple, as follows:
Major network programming functions
- socket
int socket (int domain, int type, int protocol);
Assigns a descriptor for a socket and the resources it uses according to the specified address family, data type, and protocol.
Domain : protocol family. commonly used af_inet, Af_inet6, af_local, Af_route where af_inet represents the use of the IPv4 address
type : Socket type. Commonly used socket types are, Sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket and so on
protocol : protocol. Eat commonly used protocols are, IPPROTO_TCP, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, etc.
- Bind
int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);
Bind specific address information and sockets in an address family
Sockfd:socket description Word, which is the socket reference
Addr: The protocol address to bind to the SOCKFD
Addrlen: Length of Address
Usually when the server is started to bind a well-known address (such as IP address + port number) to provide services, the client can be used to connect the server, and the client does not specify, there is a system automatically assigned a port number and its own IP address combination. 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 ().
- Listen
int listen (int sockfd, int backlog);
Server Boot listener socket
SOCKFD: The socket descriptor to listen on
Backlog: The maximum number of connections that the corresponding socket can queue
- Accept
int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);
After the TCP server hears the client request, it calls the Accept () function to process the client's connection request and returns the socket that communicates with the client after success
SOCKFD: Socket descriptor for server
Addr: Client's socket address
Length of the Addrlen:socket address
- Connect
int connect (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);
Client requests to connect to server based on server address information
SOCKFD: Socket description Word for Client
Addr: The server's socket address
Length of the Addrln:socket address
- Read
ssize_t Read (int fd, void *buf, size_t count);
Read the available content of the socket, i.e. receive communication information
Fd:socket Description Word
BUF: Buffer
Count: Buffer length
- Write
ssize_t Write (int fd, const void *buf, size_t count);
Writing to the socket is actually sending the content
Fd:socket Description Word
BUF: Buffer
Count: Buffer length
- Close
int close (int fd);
Close the socket FD to end the current TCP connection
Code sample server-side
main.cpp//tcpserver////Created by God Lin on 15/1/14.//Copyright (c) 2015 Arbboter. All rights reserved.//#include <sys/socket.h> #include <unistd.h> #include <sys/types.h> #include <netdb.h>/* sockaddr_in declaration */#include <stdio.h> #include <stdlib.h> #include <string.h> #includ E <arpa/inet.h>/* Inet_ntoa declaration */void start_server (unsigned int port); int main (int argc, const char * argv[]) {St Art_server (22221); return 0;} void start_server (unsigned int port) {int fd_server = socket (af_inet, sock_stream, 0); Set address sockaddr_in addr_server; memset (&addr_server, 0, sizeof (addr_server)); addr_server.sin_family = af_inet; ADDR_SERVER.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Addr_server.sin_port = htons (port); Socket bind with Address if (bind (fd_server, struct sockaddr*) &addr_server, sizeof (struct sockaddr)) = =-1) { printf ("Bind socket failed\n"); ReturN }//server socket start list, waitting client to connect//This client_max refers to simultaneous connection number if (Listen (fd_server, 10) = = -1) {printf ("Start listen socket failed\n"); Return } int fd_client =-1; Sockaddr_in addr_client; socklen_t Addr_len = 0; int nconnect = 10; while (--nconnect>0) {//must be set to length otherwise failed! Addr_len = sizeof (struct sockaddr_in); Negotiate to read the information sent by the client, and then return to the client a random number fd_client = Accept (Fd_server, (struct sockaddr*) &addr_client, &a Ddr_len); if (fd_client = =-1) {printf ("Accept socket failed\n"); Return }//Create a thread to talk with client printf ("recived connection from [%s]:", Inet_ntoa (ADDR_CL IENT.SIN_ADDR)); Read Message char buf[512] = {0}; Read (fd_client, buf, sizeof (BUF)); printf ("%s\n", buf); Return message sprintf (BUF, "magic number is:%d", Rand ()%1000); Write (Fd_client, buf, strlen (BUF)); Close this communication close (fd_client); } close (Fd_server);}Client code
main.cpp//tcpserver////Created by God Lin on 15/1/14.//Copyright (c) 2015 Arbboter. All rights reserved.//#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/ socket.h> #include <sys/types.h> #include <netdb.h> #include <string.h> #include <arpa/inet.h > #include <string.h>void start_client (const char* SERVER_ADDR, int port); int main () {start_client ("127.0.0.1") , 22221); return 0;} void Start_client (const char* SERVER_ADDR, int port) {int sockfd_server; struct sockaddr_in addr_server; Create Socket Sockfd_server = socket (af_inet, sock_stream, 0); if (Sockfd_server = =-1) {printf ("init socket failed\n"); Return }//Set server address memset (&addr_server, 0, sizeof (addr_server)); addr_server.sin_family = af_inet; ADDR_SERVER.SIN_ADDR.S_ADDR = inet_addr (server_addr);; Addr_server.sin_port = htons (port); Connect server if (connect (Sockfd_server, (struct sockaddr *) &addr_server,sizeof (struct sockaddr) ==-1) {printf ("Connect Server failed\ n "); Return } char buf[512] = {0}; sprintf (buf, "Hi, I ' M hello!"); Write (Sockfd_server, buf, strlen (BUF)); Get server return information size_t nread = Read (Sockfd_server, buf, sizeof (BUF)); Buf[nread] = ' + '; printf ("recived from server:%s", buf); Close (sockfd_server);}
TCP BASIC Programming for Linux