A basic TCP socket programming This article comes from: http: //sunsland.top263.net Author: (2001-10-22 12:00:00)
Overview Socket () - Get a file descriptor! Bind () - Which port we are? Connect () - hello! Listen () - Is anyone called me? Accept () - "Thank you for calling port 3490." Send () and RECV () - Talk to Me, Baby! Sendto () and Recvfrom () - Talk to Me, Dgram-StyleClose () and Shutdown ( ) - Rolling! getPeername () - Who are you? gethostname () - Who are I? DNS - You said "White House", I said "198.137.240.100"
Socket Function: Specify Protocol Type Definition: #include #include int socket (int name, int type, int protocol); Return value error: -1 success: Set connection Socket File Descriptor (socket) SockFD socket function Specifies the protocol (IPv4, IPv6 or UNIX) and socket types (byte streams, datagrams, or original sockets). But there is no designation of a local protocol address or a remote protocol address. Understand the way SocketSocket uses UNIX file descriptors and other program communication. When performing any form of I / O, UNIX program is read or written a file descriptor. A file descriptor is just an integer associated with an open file. This file may be a network connection, FIFO, pipeline, terminal, file on disk or what other things. All things in UNIX are files! Therefore, when communicating with other programs on the Internet, you need to pass the file descriptor. Use the system call socket () to get the file descriptor of the network communication. He returns socket descriptor and then calls Send () and RECV () by him. So why don't you use the general call read () and Write () to communicate through the interface interface? A simple answer is: you can use a general function! The detailed answer is: Use Send () and Recv () to make you better control data transfer.
Connect function function: establish a connection definition with the TCP server: #include #include int connect (int sockfd, struct sockaddr * serv_addr, int addrlen); // sockfd is a system Call socket () returned to interface file descriptor serv_addr is a data structure saved with the destination port and IP address Struct Sockaddr // addrlen set to sizeof (struct sockaddr) Connect inspire TCP three-way handshake process server must be ready to accept foreign Connection. This is done by calling the socket, bind, and 1isten function, called passive open (PASSIVE OPEN) Customer Opening (Active OPN) by calling Connect. This causes the customer TCP to send a SYN segment (indicating synchronization) that tells the server client's initial serial number of the data sent in the (to be established). The server must confirm the customer's SYN, and you have to send a SYN segment, which contains the server of the data that will be transmitted in the same connection. The server sends SYN to the customer in a single summary and the ACK of the customer SYN. Customers must confirm the server's SYN. Connect error Return error Cause: Did not receive SYN response (server timeout, 75S) Return value: ETIMEDOUT user output: Connection Time Out. Error Reason: Receive the RST Response (HARD Error) SYN arrived at the server, but the server None This port service return value: ECONNREFUSE user output: Connection Refused Cause: ICMP error: Soft error) Return value: EHOSTUNREACH Output: ENETUNREACH NO ROUTE TO HOSTBIND Function: Assign a local protocol address definition: #include #include int bind (int sockfd, const structure sockaddr * my_addr, int address; sockfd is called Socket) File descriptor. MY_ADDR is a pointer to the data structure Struct SockAddr, saves an address (ie port, and IP address) information. Addrlen is set to SizeOf (Struct SockAddr). Return: 0- Success, -1 --- Error automatically handles the address IP and port portmy_addr.sin_port = 0; / * cho3ddr.sin_addr.s_addr = incdr_Addr.s_addr = IP address * / bind () ourselves yourself: assign 0 to my_addr.sin_por. Automatically fill in the IP address of the machine he runs: MY_ADDR.SIN_ADDR.S_ADDR is set to INADDR_Any.
Listen function function: Convert unconnected active sockets to a passive interface, indicating the connection request for the kernel accepts. closed -? Listen definition: #include int Listen (int Sockfd, INT backlog); SOCKFD is a socket file descriptor that calls socket () returns. Backlog is the number of connections allowed in the entry queue. The two queues of the listener interface have not completed the connection queue: SYN_RECV has completed the connection queue (Established When a customer's SYN arrives, if the two queues are full, TCP will ignore the partial segment. And do not send the RSTACCEPT function function: return the next completed connection definition #include int access (int suckfd, struct sockaddr * cliaddr, int * addrlen); return to success: 1. Cliaddr: Protocol Address and Address Size of Customer Process 2. New Set Interface Description Word (Connected Interface Description Word) Listel Set Description Word Listening Socket Descriptor A given server often only generates a monitored interface, and Already existed until the server is turned off. The connected interface Description The word Connected Socket Descriptor core creates a connected interface for each accepted customer connection. When the server completes the service of a customer, turn off the connected interface. Port of 1024: Super User
Fork function function: Directive new process create new process definition: #include PID_T fork; return 0 in the child process, return -1 when the process ID of the sub-process in the parent process error is returned to -1, Calling a typical application of two FORKs once: 1. A process can create a copy for yourself. When a copy is processed, other copies can perform other tasks. This is a very typical web server. 2. A process wants to perform other programs, because the unique way to create a new process is to call the Fork, the process first calls for a copy, then one copy (usually for the child process) calls Exec to replace yourself to execute new programs.
(http://www.fanqiang.com)
-------------------------------------------------- -------------------------------------------------- -------------------------
-------------------------------------------------- -------------------------------------------------- -------------------------
Concurrent server
Iterative Server ITERATIVE Server Single Process Concurrent Server Concurrent Server Multi-Process When Connection is established, Accept returns, the server calls the Fork child process to serve the customer (through the connfd connected to the socket interface), the parent process waits for another connection (through the Listenfd listener interface ). After the child process starts to handle new customers, the parent process turns off the connected interface.
Each file or socket has an access count, which maintained in the file entry, which indicates the number of descriptions that are currently pointing to the file or socket. After returning from SOCK, the file table item associated with ListenFD is 1, and after returning from accept, the file table item associated with connfd is also 1. When the Fork returns, the two descriptors are associated with the documentation with the sub-process sharing and the two sets of interfaces. When the parent process turns off the connfd, the access count value will be reduced from 2 to 1. The description word is only turned off when the access count value is 0, which will meet the .close function when the child process is turned off after a certain child process closes connfd.
Function: Do "Closed Tag" and return the process immediately. The access counter of the socket description word will be reduced by 1. When the access counter value is 0, the four packet connection termination sequences of the TCP are thrown, thereby closing the socket. Definition: #include int close (int setfd);
GetSockName and getPeername functions
Function: getsockname: Returns the local protocol address getpeername: Returns the remote protocol address is defined: #include int getsockname (int sockfd, struct sockaddr * localaddr, int * addrlen); int getpeername (int sockfd, struct sockaddr * Peeraddr, int * addrlen;
An example program:
#include #include #include #define myport 3490 / * The port users will be connecting to * / # define backlog 10 / * How Many Pending Connections queue will hold * / main () {int sockfd, new_fd; / * listen on sock_fd, new connection on new_fd * / struct sockaddr_in my_addr; / * my address information * / struct sockaddr_in their_addr; / * connector's address information * / int sin_size ; sockfd = socket (AF_INET, SOCK_STREAM, 0); / * do some error checking * / my_addr.sin_family = AF_INET;! / * host byte order * / my_addr.sin_port = htons (MYPORT); / * short, network byte order * / my_addr.sin_addr.s_addr = INADDR_ADR_ADDR_ADR; / * Auto-Fill with my ip * / bzero (& (my_addr.sin_zero), 8); / * Zero the rest of the struct * // * don't forget you error checking for these calls: * / bind (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr)); listen (sockfd, BACKLOG); sin_size = sizeof (struct sockaddr_in); new_fd = accept (sockfd, & their_addr, & sin_size) (................................................................ .com