The likes of Java, Python, and others have ruined me. I'm trying to automate an FTP client by responding to server codes:
For example:
// I know this is ugly, please bear with me
char username[25];
strcat(username, USER); //"USER "
strcat(username, usr); // "foo"
strcat(username, "\n"); // = "USER foo\n"
char password[25];
strcat(password, PASS); //"PASS "
strcat(password, pswd); //"bar"
strcat(password, "\n"); // = "PASS bar\n"
//read/write loop
while (1) {
char* responsePtr;
serverCode = readSocket(sockfd, mybuffer);
if (serverCode == 221)
break;
if (serverCode == 220)
responsePtr = &username;
if (serverCode == 331)
responsePtr = &password;
writeSocket(sockfd, responsePtr);
}
When I try this, it works for USER, but I get some mangled text for PASS:
C->S: USER anonymous
S->C: 331 Please specify the password.
C->S: (??_?PASS random
Can anyone wiser and more experienced than myself give me some C string pointers? Clearly this isn't working out for me.
You need to initialize your strings before you concatenate to them. Arrays are not initialized by default.
For what it's worth, you can use
sprintf
to create the strings more easily:Hopefully you also realize that using fixed size buffers is a recipe for buffer overflow bugs. For security you should make sure to guard against them. It's annoying, but that's C for you: