Linux network programming 6 & mdash; use TCP to implement file server, linux Network Programming

Source: Internet
Author: User

Linux network programming 6 -- use TCP to implement file server and linux Network Programming
Requirement

After the client connects to the server, the server will transmit the corresponding files to the client to download the files.

Ideas

The master process is responsible for listen. In the cycle, every time the master process sends an accept request from the task request queue, the fork output will complete file transmission. Note: If the fork is the son, the main process will have to be the wait son. In this way, only after the file is transferred to a client can the next one be completed.

Code

Server

/*************************************** * *********************************> File Name: server. c> Author: KrisChou> Mail: zhoujx0219@163.com> Created Time: thu 28 Aug 2014 09:40:32 pm cst ********************************* ***************************************/ # include <stdio. h> # include <stdlib. h> # include <string. h> # include <sys/types. h> # include <sys/stat. h> # include <fcntl. h> # include <sys/socket. H> # include <netinet/in. h> # include <arpa/inet. h> # include <unistd. h> # include <netdb. h> # define SNDSIZE 1024*1024 // 1 M. Note that if the stack space (which can be set) is not so large, use the heap space # define FILE_NAME ". rmvb "int main (int argc, char * argv []) // exe config {/* read server contact information from the configuration file: IP address and port number */int fd_conf; fd_conf = open (argv [1], O_RDONLY); FILE * fp_conf = fdopen (fd_conf, "r"); // show the fdopen function, convert the file descriptor to the file pointer fdopen (int fd, const char * mode) char my_ip [32] = ""; int my_port; fscanf (fp_conf, "% s % d", my_ip, & my_port); close (fd_conf); fclose (fp_conf ); /* Create the server's listening socket port */int fd_listen = socket (AF_INET, SOCK_STREAM, 0); if (fd_listen =-1) {perror ("socket ");} /* bind the contact information to the socket port of the server so that the client can connect */struct sockaddr_in server_addr; memset (& server_addr, 0, sizeof (server_addr); server_addr.sin_family = AF_INET; Sources Ns (my_port); response = inet_addr (my_ip); if (-1 = bind (fd_listen, (struct sockaddr *) & server_addr, sizeof (server_addr ))) {perror ("bind"); close (fd_listen); exit (1);}/* listen */if (-1 = listen (fd_listen, 5 )) {perror ("listen"); close (fd_listen); exit (1);}/* accept */int fd_client; /* the other end of the client socket port */struct sockaddr_in client_addr;/* client contact information, which is given by the outgoing parameter of the accept function */int Len; memset (& client_addr, 0, sizeof (client_addr); len = sizeof (client_addr); while (1) {fd_client = accept (fd_listen, (struct sockaddr *) & client_addr, & len); if (fd_client =-1) {continue;} printf ("a client connect! Ip: port % s: % d \ n ", inet_ntoa (client_addr.sin_addr), ntohs (client_addr.sin_port); if (fork () = 0) {close (fd_listen ); // shut down the sub-process and the Sun Tzu process without the listen port. If (fork () = 0) {int fd_file = open (FILE_NAME, O_RDONLY); // open the file char buf [SNDSIZE] to be downloaded from the client; int snd_cnt = 0; int readn;/* read data from the file and send it to the client */while (memset (buf, 0, SNDSIZE), (readn = read (fd_file, buf, SNDSIZE)> 0) {if (send (fd_client, buf, readn, 0 )! = Readn) {printf ("send error! \ N ") ;}snd_cnt ++;} printf (" send over: % d \ n ", snd_cnt); close (fd_file); close (fd_client ); exit (0);} close (fd_client); exit (0);} close (fd_client); wait (NULL);} return 0 ;}

Client

/*************************************** * *********************************> File Name: client. c> Author: KrisChou> Mail: zhoujx0219@163.com> Created Time: thu 28 Aug 2014 11:59:20 pm cst ********************************* ***************************************/ # include <stdio. h> # include <stdlib. h> # include <string. h> # include <sys/types. h> # include <sys/stat. h> # include <fcntl. h> # include <sys/socket. H> # include <netinet/in. h> # include <arpa/inet. h> # include <unistd. h> # include <netdb. h> # define SNDSIZE 1024*1024 # define SERVER_PORT 6080 // server port int main (int argc, char * argv []) exe ip {/* socket */int fd_client; fd_client = socket (AF_INET, SOCK_STREAM, 0); if (fd_client =-1) {perror ("socket"); exit (1 );} /* struct for storing the Connected Server Information */struct sockaddr_in server_addr; memset (& server_addr, 0, sizeof (server_addr) ); Server_addr.sin_family = AF_INET; server_addr.sin_port = htons (SERVER_PORT); region = inet_addr (argv [1]);/* connect */while (connect (fd_client, (struct sockaddr *) & server_addr, sizeof (server_addr) =-1) {/* When connect returns-1, it indicates that the server has not started */sleep (1 ); printf ("connecting... \ n ");} printf (" connect success! \ N "); int fd_write = open (" txt ", O_WRONLY | O_CREAT); // The downloaded content is written to the char buf [SNDSIZE] in the local file; int readn; int recv_cnt = 0; while (memset (buf, 0, SNDSIZE), (readn = recv (fd_client, buf, SNDSIZE, 0)> 0) {write (fd_write, buf, readn); recv_cnt ++;} printf ("recv over: % d \ n", recv_cnt); close (fd_write); close (fd_client); return 0 ;}

LINUX Network Programming how does the TCP Server Client Address garbled characters?

Solution:
1. add memset (buff, 0, sizeof (buff) before client n = read (socketfd, buff, 1023 ));, this is to ensure that short data is received (you cannot ensure that the data received each time and the length of the data to be sent using TCP), and printing is also correct;
2. change the client buff [n + 1] + = '\ 0'; to buff [n] =' \ 0'; Because n is a subscript, it is already the last position;
3. change the server-side buff [n + 1] + = '\ 0'; to buff [n] =' \ 0'; Because n is a subscript, it is already the last position, and like 2nd), the plus sign should also be removed. It should be a mistake;
4. The biggest problem is to write (connectfd, buff, 1023) on the server. How can you ensure that you receive 1023 characters? You should also remove the while condition as a WHILE statement, and add the previously described memset statement, and change the write (connectfd, buff, 1023) here to write (connectfd, buff, strlen (buff )).
Wish you common progress!

Linux socket network programming code

Linux is a multi-task operating system that can run on Intel 80386 and higher-grade PCs, ARMS, MIPS, PowerPC, and other computer platforms, it has become a widely used, highly reliable, and powerful computer operating system. Linux has the advantages of small kernel, high efficiency, and open source code. It also contains the TCP/IP network protocol, it is very suitable for use in the server field, and one of the main purposes of the server is to conduct network communication. With the application and promotion of Computer Office Automation processing technology, the network is becoming increasingly popular, traditional paper-based file transmission methods are no longer suitable for development. People are looking forward to a convenient, efficient, environmentally friendly, and secure network transmission method.

Protocol overview TCP/IP is the Transmission Control Protocol/Network Protocol [1] (Transmission Control Protocol/Internet Protocol), is a Protocol family composed of multiple protocols, it defines the computer's mutual communication through the network and the communication standards between different levels of the protocol family. Figure 1 describes the implementation mechanism of Linux for the IP protocol family [2].

Linux supports BSD sockets and all TCP/IP protocols, which are implemented through the network protocol as a group of connected software layers. BSD Socket (BSD Socket) supported by common socket management software, which is the INET socket layer used to manage IP-based TCP and UDP port-to-port interconnection. From the perspective of protocol layering, IP is a network layer protocol, TCP is a reliable port-to-port transport layer protocol that uses the IP layer for packet transmission and connection-oriented, A virtual circuit is established to transmit packets between different networks, ensuring the non-loss and non-repetition of transmitted packets. User Data Protocol (UDP) also uses the IP layer to transmit packets, but it is a non-connection-oriented transport layer Protocol, when the destination Internet protocol layer receives an IP packet, it must identify the upper-layer protocol (Transport Layer Protocol) used in the packet. Therefore, in the IP header, there is a "Protocol" Domain (Protocol ). The value of this field can be used to determine the upper-layer protocol type. The biggest difference between the transport layer and the network layer is that the former provides process communication capabilities, while the latter cannot, in the sense of Process Communication, the final address of network communication is not only the host address, but also an identifier that can describe the process. For this reason, TCP/UDP proposes the Protocol Port (Protocol Port) for example, a Web server process usually uses port 80 and has these registered port addresses in the/etc/services file.

For TCP transmission, a connection must be established between transmission nodes, and then ordered packets are transmitted through the connection to ensure the correctness of transmission. The code in the IP layer is used to implement the Internet protocol, the Code adds the IP header to the transmission data, and correctly transmits the received IP packet to the TCP or UDP layer. TCP is a connection-oriented protocol, while UDP is a non-connection-oriented protocol. When a UDP packet is sent, linux does not know whether or not it has successfully reached the target host. Under the IP layer, it is a network device layer that supports all Linux network applications, such as the Point-to-Point Protocol, PPP) and Ethernet layer. Network devices do not always represent physical devices. Some of them (for example, the send-back devices) are pure software devices. network devices are different from standard Linux devices. They are not created using the Mknod command, these devices must be created and available only after the underlying software is found and initialized. Therefore, the/dev/eth0 file is only available after the kernel of the correctly configured Ethernet device driver is started. The ARP protocol is located between the IP layer and the protocol layer that supports address resolution.

Network communication principle all network communication technologies can be divided into two types: Line switching and packet switching. computer networks generally adopt packet switching, and TCP uses packet switching communication technology ,...... remaining full text>

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.