#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_LEN 256
typedef struct {
char username[MAX_LEN];
char password[MAX_LEN];
char ip[MAX_LEN];
char port[MAX_LEN];
char filepath[MAX_LEN];
char filename[MAX_LEN];
bool is_valid;
} FTPComponents;
bool splitFTPUrl(const char* url, FTPComponents* components) {
memset(components, 0, sizeof(FTPComponents));
components->is_valid = false;
if (url == NULL || strlen(url) == 0) {
return false;
}
char temp[MAX_LEN * 2];
strncpy(temp, url, sizeof(temp) - 1);
temp[sizeof(temp) - 1] = '\0';
if (strncmp(temp, "ftp://", 6) != 0) {
return false;
}
char* atSign = strstr(temp, "://");
if (atSign == NULL) {
return false;
}
*atSign = '\0';
char* creds = temp + 6;
char* colon = strchr(creds, ':');
if (colon == NULL) {
return false;
}
*colon = '\0';
strncpy(components->username, creds, MAX_LEN - 1);
char* at = strchr(colon + 1, '@');
if (at == NULL) {
return false;
}
*at = '\0';
strncpy(components->password, colon + 1, MAX_LEN - 1);
char* rest = at + 1;
char* portColon = strchr(rest, ':');
if (portColon == NULL) {
return false;
}
*portColon = '\0';
strncpy(components->ip, rest, MAX_LEN - 1);
char* slash = strchr(portColon + 1, '/');
if (slash == NULL) {
return false;
}
*slash = '\0';
strncpy(components->port, portColon + 1, MAX_LEN - 1);
char* path = slash + 1;
char* lastSlash = strrchr(path, '/');
if (lastSlash == NULL) {
strncpy(components->filepath, "", MAX_LEN - 1);
strncpy(components->filename, path, MAX_LEN - 1);
} else {
*lastSlash = '\0';
strncpy(components->filepath, path, MAX_LEN - 1);
strncpy(components->filename, lastSlash + 1, MAX_LEN - 1);
}
if (strlen(components->username) == 0 ||
strlen(components->password) == 0 ||
strlen(components->ip) == 0 ||
strlen(components->port) == 0 ||
strlen(components->filename) == 0) {
return false;
}
components->is_valid = true;
return true;
}
int main() {
const char* ftpUrl = "ftp://cdpt:cdpt2024@8.210.150.0:21/SAC/SAC/V1513/S-AC-V1513G-00-33212-803.040.13-LOG_Release_APP_25.03.18_01_CRC.bin";
FTPComponents components;
if (splitFTPUrl(ftpUrl, &components)) {
printf("Extraction successful!\n");
printf("Username: %s\n", components.username);
printf("Password: %s\n", components.password);
printf("IP Address: %s\n", components.ip);
printf("Port: %s\n", components.port);
printf("File Path: %s\n", components.filepath);
printf("Filename: %s\n", components.filename);
} else {
printf("Extraction failed! Invalid FTP URL format.\n");
if (strlen(components.username) > 0) {
printf("Partial extraction results:\n");
printf("Username: %s\n", components.username);
printf("Password: %s\n", components.password);
printf("IP Address: %s\n", components.ip);
printf("Port: %s\n", components.port);
printf("File Path: %s\n", components.filepath);
printf("Filename: %s\n", components.filename);
}
}
return 0;
}