TCP/IP programming for remote file transmission

Source: Internet
Author: User
Tags ftp file ftp file transfer telnet program htons

 

In the TCP/IP network structure, to ensure network security, network personnel often need to add a firewall on the router, prohibit unauthorized users from accessing the host using ftp and other security-related TCP/IP protocols.
Sometimes the system maintenance personnel need to use ftp to transfer some files from the Central Data Center host to the front-end network host, such as application replacement and upgrade. If you need to enable the firewall every time you transfer files, it seems that
Complicated. It would be nice to add a dedicated File Transfer module in your application.

UNIX Network Programming generally uses socket System calls. For the popular Client/Server mode, the procedure is as follows:
1. Socket System Call
For network I/O, The first thing UNIX processes at both ends of the server and client need to do is to call the socket () System Call, establish a soft socket, and specify the appropriate communication protocol. Format:
# Include
# Include
Int socket (int family, int type, int protocol)
Where: (1) family indicates a set of node families, whose values include:
AF_UNIX (UNIX internal protocol family)
AF_INET (Iternet Protocol)
AF_NS (XeroxNs protocol, which is used for TCP/IP programming)
AF_IMPLINK (IMP link layer)
(2) type indicates the socket type. values include:
SOCK_STREAM (stream socket)
SOCK_DGRAM (datagram socket)
SOCK_RAW (original socket)
SOCK_SEQPACKET (sequential grouping socket)
Generally, the combination of the first two parameters determines the protocol used. The third parameter is set to 0. If the first parameter is AF_INET, the second parameter is selected.
SOCK_STREAM, the protocol used is TCP. If SOCK_DGRAM is selected as the second parameter, the protocol used is UDP. When SOCK_RAW is selected as the second parameter
IP address. It is worth noting that not all combinations of families and types are valid. For details, refer to relevant materials. If the system call is successful, a file descriptor similar to that of another character is returned.
Use read and write to perform I/O operations on a file descriptor. When a process uses this soft socket, it must be closed (<descriptor> close (For details, refer
).
2. Bind System Call on the server
When a soft outlet is created, it is not associated with any address. You must use the bind () system call to establish an address contact for it. The format is:
# Include
# Include
Int bind (int socketfd, struct sockaddr_in * localaddr, sizeof (localaddr ));
Specifically: (1) the first parameter socketfd is the set of character descriptors returned by the socket () system call in the previous step.
(2) A structure of the second parameter bundled to the local address, which is defined in sys/netinet/in. h:
Struct sockaddr_in {
Short sin_family;/* The protocol family called by the socket () system, such as AF_INET */
U_short sin_port;/* port number in the byte format of the Network */
Struct in_addr sin_addr;/* network address in the network byte order */
Char sin_zero [8];
}
Each network program on a machine uses an independent port number. For example, the telnet program uses port 23, while the ftp file transfer program uses port 21. We are designing applications
During the program, the port number can be obtained by the getservbyname () function from the/etc/services library file, or by htons (int
Portnum) function converts any positive integer to the network byte order form to obtain, some versions of UNIX operating systems require that the port numbers below 1024 can only be used by superusers, ordinary users
The number of the port used by the program is limited to 1025 to 32767. The network address can be obtained by the gethostbyname (char * hostname) function (this function and
Getservbyname () returns all data in their structure in the bytes order of the network.) The hostname parameter is a network address in the/etc/hosts file.
The name of the corresponding machine. This function returns a structure pointer of the hostent type, which is defined in netdb. h:
Struct hostent {
Char * h_name;
Char ** h_aliases;
Int h_addrtype;
Int h_length;/* address length */
Char ** h_addr_list;
# Define h_addr h_addr_list [0];/* address */
}
(3) The third parameter is the length of the second structure parameter. If the call is successful, bind returns 0; otherwise,-1 is returned and errno is set.
3. The server-side system calls listen to make the server willing to accept the connection
Format: int listen (int socketfd, int backlong)
It is usually executed before the accept call after the socket and bind calls. The second parameter specifies the number of connections that the system can queue when waiting for the server to execute an accept call. This parameter is usually set to 5, which is also the maximum value currently allowed.
4. The server calls accept to wait for the client to call connect for connection. The format is as follows:
Int newsocket = (int socketfd, struct sockaddr_in * peer, int * addrlen );
This call gets the first connection request on the queue and creates a set of characters with the same features as sockfd. If there is no pending connection request, this call blocks the caller until a connection request arrives. Connection
After the call is successful, the peer and addlen parameters are filled with the peer address structure and address length. If you are not interested in the client address information, the two parameters are replaced with 0.
5. The client calls connect () to establish a connection with the server. Format:
Connect (int socketfd, struct sockaddr_in * servsddr, int addrlen)
After the client obtains the socket descriptor, it uses this call to establish a connection with the server. The socketfd parameter is the set of character descriptors returned by the socket () system call. The second and third parameters refer
Structure of the destination address and the length of the destination address measured in bytes (here the destination address should be the server address ). If the call is successful, 0 is returned. Otherwise,-1 is returned and errno is set.
6. Send data through a soft Outlet
Once a connection is established, the system can call read and write to send and receive data to and from the network as normal files. Read accepts three parameters: one is a set of character descriptors, and the other is data.
The buffer to be filled in. There is also an integer indicating the number of bytes to be read. It returns the actual number of bytes to be read. If an error occurs, it returns-1 and 0 at the end of the file. Write also accepts three parameters:
Character descriptor; a buffer pointing to the data to be sent, and an integer indicating the number of bytes to be written to the file. It returns the actual number of bytes to be written, and returns-1 if an error occurs. Of course, you can also call send
And recv to read and write the set of characters. The call is similar to the basic read and write System Call, but there is only one sending method parameter.
7. When exiting the program, you should close the set of characters in the normal way. The format is as follows:
Int close (socketfd)
This section describes the basic ideas and steps for network programming in UNIX Client/Server mode. It is worth noting that the system calls involved in socket programming are not within the scope of basic system calls, and the original function is in libsocket. file a. Therefore, the-lsocket option must be included when you use the cc command to compile the original program.
Now, we can start programming for the questions raised at the beginning of the article. In the network structure shown in the figure, to enable the server in the central data center to communicate with clients on the network, you must add
The route from vro1112 2221 to the client. The two clients must also add a route from vroto the server. The/etc/hosts file on the server should contain the following
Content:
1.1.1.1 server
2.2.2.2 cli1
2.2.2.3 cli2
The/etc/hosts file of the client should contain the local address information and the server address information, such as the/etc/hosts file of the cli1 client:
2.2.2.2 cli1
1.1.1.1 server
After the network environment is set up, we can write the fwq. c program on the server side to accept client connection requests and send the data read from the source file to the client. The client program khj. c sends a connection request to the server, receives data from the server, and writes the received data to the target file. The source program is as follows:
/* Server Source Code fwq. c */
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Main ()
{
Char c, buf [1024], file [30];
Int fromlen, source;
Register int k, s, ns;
Struct sockaddr_in sin;
Struct hostent * hp;
System ("clear ″);
Printf ("\ n ″);
  
Printf ("\ n \ t input file name to be transferred :″);
Scanf ("% s", file );
If (source = open (file, O_RDONLY) <0 ){
Perror ("open source file error ″);
Exit (1 );
}
Printf ("\ n \ t is transferring the file. Wait... ″);
Hp = gethostbyname ("server ″);
If (hp = NULL ){
Perror ("host address error returned !!! ″);
Exit (2 );
}
S = socket (AF_INET, SOCK_STREAM, 0 );
If (s <0 ){
Perror ("failed to get SOCKET number !!! ″);
Exit (3 );
}
Sin. sin_family = AF_INET;
Sin. sin_port = htons (1500);/* use port 1500 */
Bcopy (hp-> h_addr, & sin. sin_addr, hp-> h_length );
If (bind (s, & sin, sizeof (sin) <0 ){
Perror ("cannot bind the server address to the SOCKET number !!! ″);
Colse (s );
Exit (4 );
}
If (listen (s, 5) <0 {
Perror ("sever: listen ″);
Exit (5 );
}
While (1 ){
If (ns = accept (s, & sin, & fromlen) <0 ){
Perror ("sever: accept ″);
Exit (6 );
}
Lseek (source, OL, 0);/* each time the client connection is accepted, the source file pointer used for reading should be moved to the file header */
Write (ns, file, sizeof (file);/* Send file name */
While (k = read (source, buf, sizeof (buf)> 0)
Write (ns, buf, k );
Printf ("\ n \ t transfer completed !!! \ N ″);
Close (ns );
}
Close (source );
Exit (0 );
/* Client source code khj. c */
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Main ()
{
Char buf [1024], file [30];
Char * strs = "\ n \ t Receiving File ″;
Int target;
Register int k, s;
Struct sockaddr_in sin;
Struct hostent * hp;
System ("clear ″);
Printf ("\ n ″);
   
Hp = gethostbyname ("server ″);
If (hp = NULL ){
Perror ("error returned from server address !!! ″);
Exit (1 );
}
S = socket (AF_INET, SOCK_STREAM, 0 );
If (s <0 ){
Perror ("failed to get SOCKET number !!! ″);
Exit (2 );
}
Sin. sin_family = AF_INET;
Sin. sin_port = htons (1500);/* the port number must be the same as that used by the server program */
Bcopy (hp-> h_addr, & sin. sin_addr, hp-> h_length );
Printf ("\ n \ t is connecting to the server... ″);
If (connect (s, & sin, sizeof (sin), 0) <0 ){
Perror ("cannot connect to the server !!! ″);
Exit (3 );
}
While (k = read (s, file, sizeof (file) <= 0/* Receiving file name */
If (target = open( file, o_WRONLY | O_CREAT | O_TRUNC, 0644) <0 ){
Perror ("cannot open the target file !! ″);
Exit (4 );
}
Strcat (strs, file );
Strcat (strs, ", wait... ″);
Write (1, strs, strlen (strs ));
While (k = read (s, buf, sizeof (buf)> 0)
Write (tatget, buf, k );
Printf ("\ n \ t" received the file successfully !!! \ N ″);
Close (s );
Close (target );
}
The preceding program is successfully debugged in Sco Unix System v3.2 and Sco TCP/IP Rumtime.

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.