Question

write a socket network programming in C++ or C (please write your source code) Requirement :...

write a socket network programming in C++ or C (please write your source code)
Requirement :
Basic : implement a client and a server similiar with ftp protocol, complete the basic function of file transfer.
- list the files/ directories
-change working-directory
-download file/s
-Upload files/s

0 0
Add a comment Improve this question Transcribed image text
Answer #1

A Simple FTP Client Implemented in C Language

To download files from an FTP server, you need to implement a simple FTP client.

FTP (File Transfer Protocol) is an application layer protocol in the TCP/IP protocol group.

The FTP protocol uses string format command words, and each command is a line string ending with'\r\n'.

Client send format is: Command + space + parameter + format of'\r\n'

The server returns in the following format: status code + space + Prompt string + "\r\n". The code simply parses the status code.

Read and write files require a login to the server, with a special user name: anonymous, meaning anonymous.Be case sensitive.

The basic process for downloading files from an FTP server is as follows:

1. Establish a TCP connection. This protocol uses port 21 by default. Of course, other ports can be specified, depending on the configuration of the server.

2. After a successful connection, the server sends a line of welcome text, for example, 220 welcome.
The number 220 on the left indicates the ready state, followed by a space and prompt text.
When parsing the command response, you only need to get the previous number.

3. After receiving the welcome message, the login will begin. Send the user name with the USER command first, and the server will return to 331 status.
Then use the PASS command to send the login password. The server returns 530 for an incorrect password and 230 for the correct password.
Send: USER anonymous
Receive: 331 Anonymous login ok, send your complete email address as your password
Send: PASS anonymous
Receive: 230 Anonymous access grand, restrictions apply

4. After successful login, send another TYPE I command into binary mode, so that when file data is obtained, it will be sent as a binary byte stream.
Avoid sending file data in ASCII format.

5. Get file length
Send: SIZE/path/filename
Failure: 550/path/filename: No such file or directory
Success: 213 [filesize]
The return [filesize] is a decimal number indicating the size of the file in bytes

6. Download Files
Send the PASV command before downloading the file and enter passive mode, so the FTP server will open a new port to receive file data.
After the client successfully connects to the data port, it sends the RETR command to request the download of the file, then the file data will be sent from the new port, the file transfer is completed, and the server automatically closes the data port.
Send: PASV
Receive: 227 Entering Passive Mode (145,24,145,107,207,235).
The five numbers in the back brackets represent the IP address and port number respectively. The port number is divided into high 8 bits and low 8 bits, and the high 8 bits are first
The example here shows an IP address of 145.24.145.107 and a port number of 53227 (formula: 207 * 256 + 235).

Send: RETR/path/filename
Receive: 150 Opening BINARY mode data connection for/path/filename (54 bytes)
> > > >> Receive file data from data port
Receive: 226 Transfer complete

7. Upload Files

Uploading a file is similar to downloading a file by sending a PASV command, getting to the data port, and then sending a STOR command to request the file to be uploaded.
The difference is that the upload file is to write file data to this data port. After writing the data, the client actively disconnects the TCP connection to the data port, and the server returns a status of successful upload.
Send: PASV
Receive: 227 Entering Passive Mode (145,24,145,107,207,235).
Send: STOR/path/filename
Receive: 150 Opening BINARY mode data connection for/path/filename
> > > >> Write data to the data port
Receive: 226 Transfer complete

=======================================

Common status codes for FTP are as follows:

110 Restart tag reply.
120 services are ready to start in nnn minutes.
125 Data connection is open and transfer is starting.
150 Files are in good condition and ready to open data connection.
2xx-Positive Complete Reply An operation has been successfully completed.Clients can execute new commands.
200 Command OK.
202 No commands executed, there are too many commands on the site.
211 System Status, or System Help Reply.
212 Directory status.
213 File status.
214 Help message.
215NAME system type, where NAME is the official system name listed in the AssignedNumbers document.
220 The service is ready to execute the new user's request.
221 Service closes control connection.If appropriate, please log off.
225 Data connection open, no transfer in progress.
226 Close the data connection.The requested file operation succeeded (for example, transferring files or discarding files).
227 enters passive mode (h1,h2,h3,h4,p1,p2).
230 users logged in to continue.
250 The requested file operation is correct and complete.
257 "PATHNAME" has been created.
3xx - The positive intermediate reply to this command was successful, but the server needs more information from the client to complete processing the request.
331 The user name is correct and a password is required.
332 Login account is required.
350 The requested file operation is awaiting further information.
4xx-Transient Negative Complete Reply The command was unsuccessful, but the error was temporary.If the client retries the command, it may execute successfully.
421 Service unavailable, closing control connection.If the service determines that it must shut down, it sends this response to any command.
425 Unable to open data connection.426Connectionclosed;transferaborted.
450 The requested file operation was not performed.Files are not available (for example, files are busy).
451 The requested operation terminated abnormally: a local error is being processed.
452 The requested operation was not performed.Insufficient system storage space.
5xx - Permanent negative Complete reply to this command is unsuccessful, error is permanent.If the client retries the command, the same error will occur again.
500 Syntax error, command unrecognized.This may include errors such as command line being too long.
501 has a syntax error in the parameter.
502 Command not executed.
503 Bad command sequence.
504 The command for this parameter was not executed.
530 is not logged in.
532 Storage files require an account.
550 did not perform the requested operation.The file is not available (for example, no file was found, no access rights).
551 requested operation terminated abnormally: unknown page type.
The file operation requested by 552 terminated abnormally: storage allocation exceeded (for current directory or dataset).
553 The requested operation was not performed.File name not allowed.

Program in C:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "socket.h"
#include "log.h"
#include "ftp.h"

static int  m_socket_cmd;
static int  m_socket_data;
static char m_send_buffer[1024];
static char m_recv_buffer[1024];

//Command Port, Send Command
static int ftp_send_command(char *cmd)
{
        int ret;
        LOG_INFO("send command: %s\r\n", cmd);
        ret = socket_send(m_socket_cmd, cmd, (int)strlen(cmd));
        if(ret < 0)
        {
                LOG_INFO("failed to send command: %s",cmd);
                return 0;
        }
        return 1;
}

//Command Port, Receive Answer
static int ftp_recv_respond(char *resp, int len)
{
        int ret;
        int off;
        len -= 1;
        for(off=0; off<len; off+=ret)
        {
                ret = socket_recv(m_socket_cmd, &resp[off], 1);
                if(ret < 0)
                {
                        LOG_INFO("recv respond error(ret=%d)!\r\n", ret);
                        return 0;
                }
                if(resp[off] == '\n')
                {
                        break;
                }
        }
        resp[off+1] = 0;
        LOG_INFO("respond:%s", resp);
        return atoi(resp);
}

//Set FTP server to passive mode and resolve data ports
static int ftp_enter_pasv(char *ipaddr, int *port)
{
        int ret;
        char *find;
        int a,b,c,d;
        int pa,pb;
        ret = ftp_send_command("PASV\r\n");
        if(ret != 1)
        {
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 227)
        {
                return 0;
        }
        find = strrchr(m_recv_buffer, '(');
        sscanf(find, "(%d,%d,%d,%d,%d,%d)", &a, &b, &c, &d, &pa, &pb);
        sprintf(ipaddr, "%d.%d.%d.%d", a, b, c, d);
        *port = pa * 256 + pb;
        return 1;
}

//Upload Files
int  ftp_upload(char *name, void *buf, int len)
{
        int  ret;
        char ipaddr[32];
        int  port;
        
        //Query data address
        ret=ftp_enter_pasv(ipaddr, &port);
        if(ret != 1)
        {
                return 0;
        }
        ret=socket_connect(m_socket_data, ipaddr, port);
        if(ret != 1)
        {
                return 0;
        }
        //Preparing for upload
        sprintf(m_send_buffer, "STOR %s\r\n", name);
        ret = ftp_send_command(m_send_buffer);
        if(ret != 1)
        {
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 150)
        {
                socket_close(m_socket_data);
                return 0;
        }
        
        //Start uploading
        ret = socket_send(m_socket_data, buf, len);
        if(ret != len)
        {       
                LOG_INFO("send data error!\r\n");
                socket_close(m_socket_data);
                return 0;
        }
        socket_close(m_socket_data);

        //Upload complete, wait for response
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        return (ret==226);
}

//Download Files
int  ftp_download(char *name, void *buf, int len)
{
        int   i;
        int   ret;
        char  ipaddr[32];
        int   port;
    
        //Query data address
        ret = ftp_enter_pasv(ipaddr, &port);
        if(ret != 1)
        {
                return 0;
        }
        //Connect data ports
        ret = socket_connect(m_socket_data, ipaddr, port);
        if(ret != 1)
        {
                LOG_INFO("failed to connect data port\r\n");
                return 0;
        }

        //Ready to download
        sprintf(m_send_buffer, "RETR %s\r\n", name);
        ret = ftp_send_command(m_send_buffer);
        if(ret != 1)
        {
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 150)
        {
                socket_close(m_socket_data);
                return 0;
        }
        
        //Start downloading and the server will automatically close the connection after reading the data
        for(i=0; i<len; i+=ret)
        {
                ret = socket_recv(m_socket_data, ((char *)buf) + i, len);
                LOG_INFO("download %d/%d.\r\n", i + ret, len);
                if(ret < 0)
                {
                        LOG_INFO("download was interrupted.\r\n");
                        break;
                }
        }
        //Download complete
        LOG_INFO("download %d/%d bytes complete.\r\n", i, len);
        socket_close(m_socket_data);
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        return (ret==226);
}

//Return file size
int  ftp_filesize(char *name)
{
        int ret;
        int size;
        sprintf(m_send_buffer,"SIZE %s\r\n",name);
        ret = ftp_send_command(m_send_buffer);
        if(ret != 1)
        {
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 213)
        {
                return 0;
        }
        size = atoi(m_recv_buffer + 4);
        return size;
}

//Logon Server
int ftp_login(char *addr, int port, char *username, char *password)
{
        int ret;
        LOG_INFO("connect...\r\n");
        ret = socket_connect(m_socket_cmd, addr, port);
        if(ret != 1)
        {
                LOG_INFO("connect server failed!\r\n");
                return 0;
        }
        LOG_INFO("connect ok.\r\n");
    //Waiting for Welcome Message
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 220)
        {
                LOG_INFO("bad server, ret=%d!\r\n", ret);
                socket_close(m_socket_cmd);
                return 0;
        }
        
        LOG_INFO("login...\r\n");
    //Send USER
        sprintf(m_send_buffer, "USER %s\r\n", username);
        ret = ftp_send_command(m_send_buffer);
        if(ret != 1)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 331)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        
    //Send PASS
        sprintf(m_send_buffer, "PASS %s\r\n", password);
        ret = ftp_send_command(m_send_buffer);
        if(ret != 1)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 230)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        LOG_INFO("login success.\r\n");
        
    //Set to binary mode
        ret = ftp_send_command("TYPE I\r\n");
        if(ret != 1)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        ret = ftp_recv_respond(m_recv_buffer, 1024);
        if(ret != 200)
        {
                socket_close(m_socket_cmd);
                return 0;
        }
        return 1;
}

void ftp_quit(void)
{
        ftp_send_command("QUIT\r\n");
        socket_close(m_socket_cmd);
}

void ftp_init(void)
{
        m_socket_cmd = socket_create();
        m_socket_data= socket_create();
}
Add a comment
Know the answer?
Add Answer to:
write a socket network programming in C++ or C (please write your source code) Requirement :...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write technical report about the socket programming which should include the followng: Introduction about the socket...

    Write technical report about the socket programming which should include the followng: Introduction about the socket programming Advantages of socket programming Create TCP/IP Client (the source code in any language) socket program that performs the following steps: a. Initializes Winsock. b. Creates a socket. c. Connects to the server. d. Sends and receives data. e. Disconnects. create TCP/IP Server socket program that performs the following steps: a. Initializes Winsock. b. Creates a socket. c. Listen for client. d. Receives and...

  • *****Can someone please HELP me with this assignment please, I am struggling with this assignment and...

    *****Can someone please HELP me with this assignment please, I am struggling with this assignment and would appreciate some help, needs to be done in c/c++ ******* (100 marks) In this problem, you will write a file transfer program for transferring files between two computers connected by a network. The protocol that you will implement is called the Simple File Transfer Protocol (SFTP). The complete description for SFTP is given below. PART 1 SFTP is a simple protocol for transferring...

  • Practice socket programming with threads: Write an 'echo' server using UDP. (This server does not need...

    Practice socket programming with threads: Write an 'echo' server using UDP. (This server does not need to be multi-threaded, but make sure that you do know how to implement a multi-threaded server when asked.) Each request is handled by replying to the client with the unmodified string the client sent. Also, write an 'echo' client to test your server. Each client will send 20 sequentially numbered messages to the server & receive the replies. This code needs to be in...

  • Implement a Linux application (C program) that shows a file listing of a directory in the...

    Implement a Linux application (C program) that shows a file listing of a directory in the terminal. In the list include the file name, size, and date modified. This would mimic what you see in a standard file explorer/ftp. Allow for 2 optional flags: -n: will sort the given directories files by size -m: will sort the given directories files by last modified Notes: The -n and -m flags are optional, allow for one or both to be used, or...

  • In Python, make changes in the client code, so that the client allows the user to...

    In Python, make changes in the client code, so that the client allows the user to continue to send multiple requests until the user types in “Quit”. This means that the client process should not exit after the user sends one request and receives one response. Instead, the client process should be able to receive subsequent inputs from the user. You need to have a loop in the client code, so that it can accept the user request until the...

  • Using network sockets, write a C program called client that receives three command-line arguments in the...

    Using network sockets, write a C program called client that receives three command-line arguments in the form: client host port file and sends a request to a web server. The command-line arguments are hostRepresents the web server to connect to port Represents the port number where a request is sent. Normally an HTTP request is sent over port 80, but this format allows for custom ports file Represents the file requested from the web server Your program should create a...

  • 166 Chapter 8: TCP/IP Applications Getting Down to Business The way network communication all those ls...

    166 Chapter 8: TCP/IP Applications Getting Down to Business The way network communication all those ls and Os) goes in and out of a machine physically is through the NIC (network interface card). The way network communication goes in and out of a machine logically though, is through a program or service. A service is a program that runs in the background, independent of a logon, that provides functionalities to a system. Windows client machines, for instance, have a Workstation...

  • File dir = new File("c:\\programming"); String newFileName = "list.txt"; Write a code that creates a new...

    File dir = new File("c:\\programming"); String newFileName = "list.txt"; Write a code that creates a new file specified by newFileName in the directory specified by dir.

  • I need help with this assignment, please; Programming Assignment 3: UDP Pinger Lab In this lab,...

    I need help with this assignment, please; Programming Assignment 3: UDP Pinger Lab In this lab, you will study a simple Internet ping server written in the Java language, and implement a corresponding client. The functionality provided by these programs is similar to the standard ping programs available in modern operating systems, except that they use UDP rather than Internet Control Message Protocol (ICMP) to communicate with each other. (Java does not provide a straightforward means to interact with ICMP.)...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT