TCP/IP programming to achieve remote file transfer __ Programming

Source: Internet
Author: User
Tags ftp file sin ftp file transfer telnet program htons
In the TCP/IP network structure, in order to guarantee the network security, the network personnel often need to add the firewall on the router, prohibits the illegal user to use the FTP and so on the security harm large TCP/IP protocol to access the host. And sometimes the system maintenance personnel need to use FTP to upload some files from the central computer room host to the front-end network host, such as the replacement of the application upgrade. It would be a lot of fun to have a firewall open every time you transfer files, and it would be nice to add a special file transfer module to your application.

UNIX network programming generally uses socket (socket) system calls. For the current very popular client/server model, the program is written as follows:
1.Socket system Call
For network I/O, the first thing the UNIX process at both ends of the server and client will do is call the socket () system call, establish a soft socket, and indicate the appropriate communication protocol. The format is:
#include >sys/types.h>
#include >sys/socket.h>
int socket (int family,int type,int protocol)
Wherein: (1) family indicates the family of the set of words, and the values include:
Af_unix (UNIX Internal protocol family)
Af_inet (Iternet protocol)
Af_ns (XEROXNS protocol, TCP/IP programmed to take this value)
Af_implink (IMP link layer)
(2) type indicates socket types, and values are:
Sock_stream (Stream sockets)
SOCK_DGRAM (Datagram socket)
Sock_raw (Original socket)
Sock_seqpacket (ordinal group socket)
In general, the first two parameters can be combined to determine the protocol used, when the third parameter is set to 0, if the first parameter is af_inet, the second parameter is Sock_stream, then the protocol used is TCP, and the second parameter chooses Sock_dgram, the protocol used is UDP When the second parameter is selected Sock_raw, the protocol used is IP. It is worth noting that not all groups and types of combinations are legitimate, please refer to the relevant information. If the system call succeeds, it returns a similar file descriptor, which becomes a nested word description, and can be used as a file descriptor for I/O operations with Read and write. Close (< descriptor >) closure is required when a process finishes using the soft socket (see below for details).
2. Server-side bind system call
When a soft socket is created, it is not associated with any address and must be contacted with a bind () system call. The format is:
#include <sys/types.h>
#include <sys/socket.h>
int bind (int socketfd,struct sockaddr_in *localaddr,sizeof (localaddr));
Where: (1) The first parameter socketfd is the nested word descriptor returned by the forward socket () system call.
(2) A structure in which the second parameter is bundled to a local address, which is defined in Sys/netinet/in.h:
struct sockaddr_in{
Short Sin_family;/*socket () system call protocol family such as af_inet*/
U_short sin_port;/* network byte order port number.
struct IN_ADDR sin_addr;/* network address in byte order form * *
Char Sin_zero[8];
}
Each network program on a machine uses a separate port number, for example, the Telnet program uses port number 23, and the FTP file transfer program uses the port number 21. When we design an application, the port number can be obtained from the/etc/services library file by the Getservbyname () function, or it can be obtained by converting any positive integer into a network byte order form by the htons (int portnum) function. Some versions of the UNIX operating system stipulate that the port number under 1024 is only available to Superuser, and the port number used by the ordinary user program is limited to 1025 to 32767. The network address can be obtained by the gethostbyname (char*hostname) function (which, like Getservbyname (), returns all data in their structure in the form of a network byte order), and the parameter hostname to/etc/ The name of the machine that corresponds to a network address in the Hosts file. The function returns a struct pointer of type hostent, and the hostent structure 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 struct parameter, and if the call succeeds, BIND returns 0, otherwise it returns-1 and sets the errno.
3. Server-side system call listen, so that the server is 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 indicates how many connection requirements the system can queue while waiting for the server to perform a accept call. This parameter is often specified as 5 and is currently the maximum allowable value.
4. The server invokes accept to wait for the client to invoke connect. The format is as follows:
int newsocket= (int socketfd,struct sockaddr_in *peer,int*addrlen);
The call obtains the first connection request on the queue and establishes a SOCKFD with the same attributes as the. If there are no pending connection requests, this call blocks the caller until a connection request arrives. When the connection succeeds, the call populates the parameters peer and Addlen with the address structure and address length on the end, and if the client's address information is not interesting, the two arguments are replaced with 0.
5. The client calls connect () to establish a connection with the server. The format is:
Connect (int socketfd,struct sockaddr_in *servsddr,int addrlen)
After the client obtains the socket descriptor, the use this call to establish a connection to the server, with the parameter socketfd as the nested-word descriptor returned by the socket () system call, and the second and third parameters are the structure of the destination address and the length of the destination address measured in bytes (where the destination address should be the server address). The call successfully returns 0, otherwise it returns-1 and sets the errno.
6. Send data through a soft socket
Once a connection is established, you can send and receive data to the network using the system call read and write as normal files. Read accepts three parameters: one is a nested-word descriptor, a buffer for data to be populated, and an integer that indicates the number of bytes to read, returns the number of bytes actually read, returns 1 when an error occurs, and returns 0 when the end of the file is encountered. Write also accepts three parameters: one is a nested-word descriptor; A buffer that points to the data that needs to be sent, and an integer that indicates the number of bytes to write to the file, returns the number of bytes actually written, and returns 1 when an error occurs. Of course, send and recv can also be invoked to read and write to a nested word, which is similar to the basic read and write system calls, with just one more method parameter to send.
7. When exiting the program, you should close the word in the normal way. The format is as follows:
int Close (SOCKETFD)
The basic ideas and steps of UNIX client/server mode network programming are described earlier. It is worth pointing out that the system calls involved in the socket programming are not part of the basic system call scope, and their function is in the libsocket.a file, so you need to take the-lsocket option when compiling the original program with the CC command.
Now we can start programming on the questions raised at the beginning of the article. In the network structure of the diagram, in order to enable the server in the center room to communicate with the clients on the network, the router 1?1?1?2 to the client is added to the server side, and the two clients must add routes 2?2?2?1 to the server via the router. The following content should be included in the server's/etc/hosts file:
1.1.1.1 Server
2.2.2.2 Cli1
2.2.2.3 Cli2
The client's/etc/hosts file should have native address information and server address information, such as the/etc/hosts file for 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, responsible for accepting the client's connection request and sending 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 side, and writes the received data to the destination file. The source program is as follows:
/* Server source program fwq.c*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <sys/netinet/in.h>
#include <netdb.h>
#include <errno.h>
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 (″
″);
  
printf (″

Enter the file name to transfer: ″);
scanf (″%s″,file);
if ((Source=open (file,o_rdonly)) <0) {
Perror (″ source file open error ″);
Exit (1);
}
printf (″
In the transfer file, wait ... ″);
Hp=gethostbyname (″server″);
if (hp==null) {
Perror (″ return host address information wrong!!! ″);
Exit (2);
}
S=socket (af_inet,sock_stream,0);
if (s<0) {
Perror (″ failed to get the 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);/* Move the source file pointer for reading to the file header each time the client connection is accepted * *
Write (ns,file,sizeof (file)); * Send file name/*
while ((K=read (source,buf,sizeof (BUF)) >0)
Write (ns,buf,k);
printf (″

Transmission COMPLETE!!!
″);
Close (NS);
}
Close (source);
Exit (0);
/* Client source program khj.c*/
#include >stdio.h>
#include >sys/types.h>
#include >sys/fcntl.h>
#include >sys/socket.h>
#include >sys/netinet/in.h>
#include >netdb.h>
#include >errno.h>
#include >string.h>
Main ()
{
Char buf[1024],file[30];
Char *strs=″

Receiving file ″;
int target;
register int k,s;
struct sockaddr_in sin;
struct Hostent *hp;
System (″clear″);
printf (″
″);
   
Hp=gethostbyname (″server″);
if (hp==null) {
Perror (″ return server address information wrong!!! ″);
Exit (1);
}
S=socket (af_inet,sock_stream,0);
if (s<0) {
Perror (″ failed to get the socket number!!! ″);
Exit (2);
}
Sin.sin_family=af_inet;
Sin.sin_port=htons (1500);//* port number must be consistent with server application/*
Bcopy (hp->h_addr,&sin.sin_addr,hp->h_length);
printf (″

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/* receive 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 (″

Received file Success!!!
″);
Close (s);
Close (target);
}
The above procedures are debugged in the SCO Unix System v3.2 and SCO TCP/IP rumtime environment.

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.