简体   繁体   中英

libcurl, how to use string as a password?

Following this example:

https://github.com/curl/curl/blob/master/docs/examples/smtp-tls.c

I managed to get it to work by setting the password as such:

curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");

However, I want to set the password up as a string, ie:

string myPassword = "password";
curl_easy_setopt(curl, CURLOPT_PASSWORD, myPassword);

When I do this however, I get an error

curl_easy_perform() failed: Login denied

I double checked and have the program print the values of the original password and the string before it sends. They are exactly the same. I have two functions to test this on. They are almost entirely identical except that one uses a hardcoded password and the other uses the string. The hard coded one works fine, but the one that uses a string is having login issues. How could I fix this?

The CURLOPT_PASSWORD option expects a char* , not a std::string . You are passing the wrong type. The library is interpreting your data in the "wrong" way and getting nonsense.

This is not diagnosed because curl_easy_setopt uses varargs to take arbitrary parameters of varying types, depending upon the option being set. (Ideally your compiler would have rejected or at least warned about the program, but that's the cost of working with type-unsafe C libraries!)

You can pass the C-string version of your string using std::string::c_str() , like this:

curl_easy_setopt(curl, CURLOPT_PASSWORD, myPassword.c_str());

There exists a project named curlpp which purports to be a type-safe wrapper around libcurl, and this might be worth a look.

It fails because curl_easy_setopt() is expecting a C style string, (ie char * ).

What you should do in this case is convert the std::string to a C style string using .c_str() .

So you should pass password by doing:

std::string myPassword = "password";
curl_easy_setopt(curl, CURLOPT_PASSWORD, myPassword.c_str());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM