Try to connect Mysql but FAILED - c++

I tried to connect MySQL.
But it seems like something goes wrong and I cannot get it.
I'm basically sending a simple SELECT statement to the database and checking if the operation was successful or not.
Unfortunately, this always outputs "Failed!"
#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;
int main() {
const char *db = "test";
const char *server = "localhost";
const char *user = "root";
const char *password = "111222";
int port = 3306;
const char *sql = "select 1";
MYSQL *con = mysql_init(NULL);
// con = mysql_init(con);
if (con == NULL) {
cout << "Error:" << mysql_error(con) << endl;
exit(1);
}
MYSQL *new_con = mysql_real_connect(con, server, user, password, db, port, NULL, 0);
if (new_con != NULL) {
cout << "Successful!" << endl;
} else {
cout << "Failed!" << mysql_error(new_con) << endl;
}
int ret = mysql_query(new_con, sql);
if (ret != 0) {
cout << "error: " << mysql_error(new_con) << endl;
}
return 0;
}

Adapted from https://dev.mysql.com/doc/c-api/8.0/en/mysql-real-connect.html
MYSQL mysql;
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,"localhost","root","111222","test",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}
else {
cout << "Successfully connected." << endl;
}
What does this sample code print ?

Related

cplusplus connet mysql show data question

**``` c++ connect mysql
1.
Heading
#include <mysql/mysql.h>
#include <iostream>
#include<stdio.h>
#include <unistd.h>
using namespace std;
MYSQL *conn;MYSQL_RES *res;MYSQL_ROW row;
int main(int argc,char **argv)
{
const char *sever = "127.0.0.1"; //主机
const char *user = "root"; //用户名
const char *password = "root"; //用户密码
const char *database = "demo"; //数据库名称
conn = mysql_init(NULL);
if(!mysql_real_connect(conn,sever,user,password,database,3306,NULL,0))
{
cout << "connect error" << endl;
return 0;
}
mysql_set_character_set(conn,"utf8");
while(1==1){//where there not work
cout<<"enter while"<<endl;
sleep(2);
cout<<"link ok"<<endl;
if(mysql_query(conn,"select * from person"))
{
cout << "query error" << endl;
return 0;
}
//res = mysql_store_result(conn);
res = mysql_use_result(conn);
while((row = mysql_fetch_row(res)) != NULL)
{
cout << row[0] << '\t' << row[1] << '\t' << row[2] << '\t'
<< row[3] << '\t' << row[4] << endl;
}
cout<<"query end"<<endl;
}
mysql_free_result(res);
mysql_close(conn);
return 0;
}
```
it can show data from mysql.but why it not cycle.the while doesn't work?
i have tried many conform to explain this .but no any one can help my ,some one who can tell my why .

Why does server output for separate clients go to the same terminal?

I'm working on a client-server application for my Operating Systems class that is supposed to simulate sales of airplane tickets. We are directed to make it so that the main thread on the TCP server is listening for incoming connections and then, as soon as we receive a client connection, creates a new thread to handle that connection. After a lot of initial confusion, I believe I have the program in a mostly-functioning state.
The problem I'm having now is that when I run all the clients from separate terminals (whether it be 2 or 5 or any other number), all the output from the server comes into the most recent terminal that I have launched it on. This isn't a huge deal in and of itself but it also means that when I use Ctrl+C to close the process running on that last terminal, it exits all clients from the server (which is a problem).
So my questions are:
1. Why is all the output from the server being directed to a single terminal rather than sending the responses to the terminal that each client process was launched from?
2. Why do all clients quit as soon as I end the process in terminal 5?
Picture of the terminals for all the clients and the server (may have to open in new tab to see everything).
Server.cpp (Needs my other class Plane.cpp to compile which I can provide if needed, but I don't think any code in there is relevant to the issue I'm facing):
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <pthread.h>
#include "Plane.h"
using namespace std;
// default plane sizing
const int DEFAULT_ROWS = 26;
const int DEFAULT_COLUMNS = 6;
// Set up global variables for threads to access (yikes)
int rows, cols;
Plane* plane;
pthread_mutex_t mutexL = PTHREAD_MUTEX_INITIALIZER;
static int clientSocket;
int connections = 0;
void *connection_handler(void*);
struct argList {
string arg;
int row, col;
};
bool argParser(string input, argList &argL) {
stringstream ss;
ss << input;
try {
ss >> argL.arg >> argL.row >> argL.col;
} catch (exception e) {
cout << "Invalid arguments\n";
return false;
}
return true;
}
string purchaseTicket(int row, int col) {
string output;
// lock this section before we use shared resource
pthread_mutex_lock(&mutexL);
cout << "Mutex locked\n";
if (plane->isAvailable(row, col)) {
plane->buyTicket(row, col);
output = "Successfully purchased ticket for row: " + to_string(row) + ", column: " + to_string(col) + "\n";
} else {
if (row > plane->getNumRows() || row < 0 || col > plane->getNumCols() || col < 0) {
output = "Invalid seat location!\n";
} else {
output = "Seat unavailable!\n";
}
}
pthread_mutex_unlock(&mutexL);
cout << "Mutex unlocked\n";
// unlock when we're done
return output;
}
string convertMatrix(Plane plane) {
char** tempMatrix = plane.getSeatMatrix();
string seats = "";
for (int i = 0; i < plane.getNumRows(); i++) {
seats += tempMatrix[i];
seats += "\n";
}
return seats;
}
// arguments to run: column row
int main(int argc, char* argv[]) {
// array of threads (thread pool)
pthread_t threads[5];
if (argc < 3) {
rows = DEFAULT_ROWS;
cols = DEFAULT_COLUMNS;
plane = new Plane(rows, cols);
} else if (argc == 3) {
rows = atoi(argv[1]);
cols = atoi(argv[2]);
plane = new Plane(rows, cols);
} else {
cout << "Only 2 arguments allowed. You entered [" << argc << "]\n";
return -1;
}
// Create socket
int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_sock == -1) {
cerr << "Failed to create socket\n";
return -1;
}
// Socket hint stuff
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr);
// Bind socket to IP and port
if (bind(listen_sock, (sockaddr*)&hint, sizeof(hint)) < 0) {
cerr << "Binding to IP/Port failed\n";
return -2;
}
// Mark the socket for listening
if (listen(listen_sock, SOMAXCONN) == -1) {
cerr << "Can't listen";
return -3;
}
char host[NI_MAXHOST];
char service[NI_MAXSERV];
int numThread = 0;
while (numThread < 5) {
cout << "Listening for connections...\n";
sockaddr_in client;
socklen_t clientSize = sizeof(client);
// accept connections
clientSocket = accept(listen_sock, (sockaddr*)&client, &clientSize);
// if connection failed
if (clientSocket == -1) {
cerr << "Failed to connect with client";
return -4;
} else {
cout << "Connection successful\n";
connections++;
}
pthread_create(&threads[numThread], NULL, connection_handler, (void*) &clientSocket);
// 0 out used memory
memset(host, 0, NI_MAXHOST);
memset(service, 0, NI_MAXSERV);
int result = getnameinfo((sockaddr*)&client,
sizeof(client),
host,
NI_MAXHOST,
service,
NI_MAXSERV,
0);
if (result) {
cout << host << " connected on " << service << endl;
} else {
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on " << ntohs(client.sin_port) << endl;
}
numThread++;
}
// join threads together
for (int i = 0; i < numThread; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
void *connection_handler(void* listen_sock) {
cout << "Thread No: " << pthread_self() << "\n-----\n";
const int clientID = connections;
// necessary variables for processing
char buff[4096];
string custMsg;
custMsg += to_string(rows) + " " + to_string(cols) + "\n";
int msgSize = strlen(custMsg.c_str())*sizeof(char);
send(clientSocket, custMsg.c_str(), msgSize+1, 0);
// Determine what we do when we receieve messages
bool firstMsg = true;
while (true) {
memset(buff, 0, 4096);
custMsg = "";
int bytesRecv = recv(clientSocket, buff, 4096, 0);
if (bytesRecv == -1) {
pthread_mutex_lock(&mutexL);
cerr << "There was a connection issue (client " << clientID << ")\n";
pthread_mutex_unlock(&mutexL);
break;
} else if (bytesRecv == 0) {
pthread_mutex_lock(&mutexL);
cout << "Client " << clientID << " disconnected" << endl;
pthread_mutex_unlock(&mutexL);
}
if (bytesRecv > 0)
cout << "Received: " << string(buff, 0, bytesRecv) << " (client " << clientID << ")\n";
// do things based on user input
string inputStr(buff);
argList args;
if (argParser(inputStr, args)) {
if (args.arg == "buy") {
string purchResult = purchaseTicket(args.row, args.col);
custMsg += purchResult;
cout << purchResult << "------\n";
} else {
custMsg = "To buy a ticket, enter: 'buy <row> <col>'\n";
}
} else {
custMsg = "Invalid argument list";
}
//custMsg += convertMatrix(*plane);
int msgSize = strlen(custMsg.c_str())*sizeof(char);
//cout << custMsg << "\n";
cout << "Responding to client: " << clientID << "\n";
send(clientSocket, custMsg.c_str(), msgSize+1, 0);
}
// Close socket
close(clientSocket);
return 0;
}
Client.cpp:
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <time.h>
using namespace std;
struct serverInfo {
string ipAddr;
int portNum;
int timeout;
};
int getRand(int max) {
return rand() % max;
}
bool getPlaneInfo(string line, int& rows, int& cols) {
stringstream ss;
ss << line;
try {
ss >> rows >> cols;
return true;
} catch (exception e) {
cout << "Critical error\n";
return false;
}
}
void getServerInfo(ifstream &serverCfg, serverInfo &conn_serv) {
// variables that we'll read into
string label, val, eq;
int i = 0;
try { // for conversion errors
while (serverCfg >> label >> eq >> val) {
if (i == 0)
conn_serv.ipAddr = val;
else if (i == 1)
conn_serv.portNum = stoi(val);
else if (i == 2)
conn_serv.timeout = stoi(val);
else
break;
i++;
}
} catch (exception e) {
e.what();
}
}
// arguments being sent in should be 'automatic' or 'manual' for method of purchasing
// followed by the .ini file containing the server connection info.
int main(int argc, char* argv[]) {
srand(time(NULL));
// we get these int variables from the first server response
int rows, cols;
bool AUTOMATIC = false;
// make sure arguments are present and valid
if (argc != 3) {
cout << "Invalid number of arguments. Exiting...\n";
}
if (strncmp(argv[1],"automatic", 9) != 0 && strncmp(argv[1],"manual", 6) != 0) {
cout << "Invlaid arguments! Please use 'manual' or 'automatic'. Exiting...\n";
return -1;
}
// check to see if they want automatic ticket purchasing
if (strncmp(argv[1], "automatic", 9) == 0) {
AUTOMATIC = true;
}
// Handle file processing in getServerInfo function
string fileName = argv[2];
ifstream SERVER_CFG;
SERVER_CFG.open(fileName);
// store values from file in conn_info
serverInfo conn_info;
if(SERVER_CFG) {
getServerInfo(SERVER_CFG, conn_info);
} else {
cout << "Invalid filename. Exiting...\n";
return -2;
}
SERVER_CFG.close();
// create socket
int conn_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn_sock < 0) {
cout << "\nFailed to Create Socket. Exiting...\n";
return -3;
}
// get port and ipAddr information that we read from file
int port = conn_info.portNum;
string ipAddr = conn_info.ipAddr;
// make hint
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddr.c_str(), &hint.sin_addr);
// try to connect to server socket i times where i is conn_info.timeout
for (int i = 0; i < conn_info.timeout; i++) {
int connectVal = connect(conn_sock, (sockaddr*) &hint, sizeof(sockaddr_in));
if (connectVal < 0 && i >= conn_info.timeout-1) {
cout << "Failed to connect (" << (i+1) << ")\n";
cout << "Failed to connect after " << (i+1) << " attempts. Exiting.\n";
return -4;
} else if (connectVal == 0) {
break;
}
cout << "Failed to connect (" << (i+1) << ")\n";
sleep(1);
}
char buff[4096];
string userInput;
bool firstMsg = true;
bool needGreet = true;
do {
userInput = "";
int sendResult;
// Send a greeting message to the server to get plane info
if (needGreet) {
userInput = "Greeting the server";
send(conn_sock, userInput.c_str(), userInput.size() + 1, 0);
needGreet = false;
continue;
}
if (AUTOMATIC && !firstMsg) {
int row = getRand(20);
int col = getRand(6);
userInput = string("buy ") + to_string(row) + " " + to_string(col);
cout << "Sending request to buy seat " << row << " " << col << "\n";
sleep(1);
} else { // get input if its manual
if (!firstMsg) {
cout << "> ";
getline(cin, userInput);
}
}
// send to server
sendResult = send(conn_sock, userInput.c_str(), userInput.size() + 1, 0);
// check if sent successfully
if (sendResult < 0) { // connection error
cout << "Failed to send to server\r\n";
continue;
}
// wait for response
memset(buff, 0, 4096);
int bytesReceived = recv(conn_sock, buff, 4096, 0);
// print response
cout << "Server> " << string(buff, bytesReceived) << "\r\n";
if (firstMsg) {
string planeInf(string(buff,bytesReceived));
if (getPlaneInfo(planeInf, rows, cols)) {
cout << "Rows: " << rows << ", Columns: " << cols << "\n";
} else {
return -5;
}
firstMsg = false;
}
} while (true);
// closing socket
close(conn_sock);
return 0;
}
Any help is greatly appreciated.
The problem is your use of global variables.
Your connection thread writes a response to clientSocket, which your main changes with every connection. Every thread will write to the same socket.
You need to create a class to hold data specific to each connection, and pass a new one of those to each thread. Do not use shared global data to hold thread-specific values.

Connect to an online db in c++

I created my database in phpMyAdmin from godaddy.com.
But i can't seem to find a way to connect to it.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
#pragma comment(lib, "mysqlcppconn.lib")
const string server = "myWebsite";
const string username = "username";
const string password = "password";
int main()
{
sql::Driver *driver;
sql::Connection *dbConn;
sql::Statement *stmt;
sql::ResultSet *res;
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement();
try
{
stmt->execute("USE test");
res = stmt->executeQuery("SELECT * FROM users");
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
sql::ResultSetMetaData *res_meta = res -> getMetaData();
int columns = res_meta -> getColumnCount();
while (res->next())
{
for (int i = 1; i <= columns; i++) {
cout << res->getString(i) << " | " ;
}
cout << endl;
}
delete res;
delete stmt;
delete dbConn;
return 0;
}
But i get this error:
Could not connect to database. Error message: Access denied for user 'username'#'IP' (using password: YES)
This code works fine with the local phpmyadmin databases.
So is there any different way to connect to databases that are hosted on a website?

Memory leak when using sqlite3 with C++

The program writes into SQLite database, the messages are received through a wireless module. But somehow there is a memory leak every time a message is received and written to the database, after about 10 000 writes the program is using 1GB of memory.
The documentation for SQLite3 with C++ says that memory leaks are prevented with sqlite3_finalize() and sqlite3_close() which are present:
#include <iostream>
#include <string>
#include <sstream>
#include "sqlite3.h"
using namespace std;
#define DB "test.db"
sqlite3 *dbfile;
bool connectDB();
void disonnectDB();
int insOrUpdate(string s);
int select(string s);
struct messageStruct_t {
float value;
};
bool isOpenDB = false;
int main() {
int counter = 0;
while (1) {
int header = 1;
int message = rand() % 3;
if (message) {
counter ++;
switch (header) {
case 1: {
messageStruct_t recMessage;
recMessage.value = 55;
int receivedSendersID = 2;
//SQL query to get foreign key
stringstream strm_select;
strm_select << "SELECT id FROM table1 WHERE sendersID="
<< receivedSendersID;
string s_select = strm_select.str();
cout << "SQL query: " << s_select << endl;
int sendersID = select(s_select);
cout << "Sender's ID: " << sendersID << endl;
if (sendersID == 0) {
cout << "Error: Sender doesn't exist\n";
} else {
stringstream strm_insert;
strm_insert << "INSERT into table2(id,value,sender_id) values("
<< counter << ", "
<< recMessage.value << ", " << sendersID << ")";
string s_insert = strm_insert.str();
cout << "SQL query: " << s_insert << endl;
insOrUpdate(s_insert);
cout << "Recorded data: " << recMessage.value << endl;
}
}
default: {
break;
}
}
}
}
}
bool connectDB () {
if (sqlite3_open(DB, &dbfile) == SQLITE_OK) {
isOpenDB = true;
return true;
}
return false;
}
void disonnectDB () {
if ( isOpenDB == true ) {
sqlite3_close(dbfile);
}
}
int insOrUpdate(string s) {
if (!connectDB()) {
return 0;
}
char *str = &s[0];
sqlite3_stmt *statement;
int result;
const char *query = str;
if (sqlite3_prepare(dbfile, query, -1, &statement, 0) == SQLITE_OK) {
result = sqlite3_step(statement);
//the documentation says that this destroys the statement and prevents memory leaks
sqlite3_finalize(statement);
return result;
}
//and this destroys the db object and prevents memory leaks
disonnectDB();
return 0;
}
int select(string s) {
if (!connectDB()) {
return 0;
}
char *str = &s[0];
sqlite3_stmt *statement;
const char *query = str;
string returned;
if (sqlite3_prepare(dbfile, query, -1, &statement, 0) == SQLITE_OK) {
int ctotal = sqlite3_column_count(statement);
int res = 0;
while (1) {
res = sqlite3_step(statement);
if (res == SQLITE_ROW) {
for (int i = 0; i < ctotal; i++) {
string s = (char*)sqlite3_column_text(statement, i);
cout << s << " ";
returned = s;
}
cout << endl;
}
if (res == SQLITE_DONE || res == SQLITE_ERROR) {
cout << "done " << endl;
break;
}
}
} else {
cout << "Can't prepare" << endl;
return 0;
}
sqlite3_finalize(statement);
disonnectDB();
int result;
stringstream convert(returned);
if (!(convert >> result)) {
result = 0;
}
return result;
}
CREATE TABLE table1 (
id INTEGER NOT NULL,
sendersID INTEGER,
PRIMARY KEY (id)
);
CREATE TABLE table2 (
id INTEGER NOT NULL,
value FLOAT,
sender_id INTEGER,
FOREIGN KEY(sender_id) REFERENCES table1 (id)
);
INSERT INTO table1(sendersID) values(2);
In your connectDB(..) call , you don't check if the database is already open before opening it again. Your memory leak is probably from the repeated mappings of this database into your memory space.
There may be other issues with this program but the change below to connectDB(..) should help with the leak on every successful insert.
bool connectDB() {
if (false == isOpenDB && sqlite3_open(DB, &dbfile) == SQLITE_OK) {
isOpenDB = true;
}
return isOpenDB;
}
You should definitely use RAII for your connections and also for your statements. There are several places where you return early without cleaning up statements and/or closing the connection.

Server - Client RSA keypair exchange

I'm new to programming and i've got this little project going for my diploma and i need help on this little code. This is a Server->Client C++ code where server generates and sends RSA Keypair to client. My problem is that both server and client codes compiled without any problem but when i start it the client side doesn't get any keypair just blank.
Here is my server code:
#include <iostream>
#include <cstdlib>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <stdio.h>
#include <string.h>
#define KEY_LENGTH 1024
#define PUB_EXP 3
#define PRINT_KEYS
#define WRITE_TO_FILE
using std::exit;
#define int_error(msg) handle_error(__FILE__, __LINE__, msg)
void handle_error(const char* file, int lineno, const char* msg)
{
std::cerr << "\n** " << file << ":" << lineno << " " << msg << "\n";
ERR_print_errors_fp(stderr);
exit(-1);
}
void init_OpenSSL()
{
std::cout << "Initializng OpenSSL library ... ";
if (!SSL_library_init())
int_error("OpenSSL initialization failed");
std::cout << "done\n";
SSL_load_error_strings();
}
DH* setup_dh()
{
DH* dh = DH_new();
if (!dh)
int_error("DH_new failed");
std::cout << "Generating DH parameters ... ";
if (!DH_generate_parameters_ex(dh, 2, DH_GENERATOR_2, 0))
int_error("DH_generate_parameters_ex failed");
std::cout << "done\n";
std::cout << "Checking DH parameters ... ";
int codes = 0;
if (!DH_check(dh, &codes))
int_error("DH_check failed");
std::cout << "done\n";
std::cout << "Generating DH keys ... ";
if (!DH_generate_key(dh))
int_error("DH_generate_key failed");
std::cout << "done\n";
return dh;
}
SSL_CTX* setup_ctx()
{
SSL_CTX* ctx;
std::cout << "Creating context ... ";
ctx = SSL_CTX_new(TLSv1_server_method());
if (!ctx)
int_error("SSL_CTX_new failed");
std::cout << "done\n";
DH* dh = setup_dh();
std::cout << "Setting DH parameters ... ";
SSL_CTX_set_tmp_dh(ctx, dh);
std::cout << "done\n";
std::cout << "Setting cipher list ... ";
if (SSL_CTX_set_cipher_list(ctx, "ADH-AES256-SHA") != 1)
int_error("Error setting cipher list (no valid ciphers)");
std::cout << "done\n";
return ctx;
}
int main()
{
init_OpenSSL();
BIO *acc, *client;
SSL* ssl;
SSL_CTX* ctx;
ctx = setup_ctx();
size_t pri_len;
size_t pub_len;
char *pri_key;
char *pub_key;
std::cout << "Generating RSA (%d bits) keypair...\n", 1024;
RSA *keypair = RSA_generate_key(1024, 3, NULL, NULL);
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
PEM_write_bio_RSAPublicKey(pub, keypair);
pri_len = BIO_pending(pri);
pub_len = BIO_pending(pub);
pri_key = (char*)malloc(pri_len + 1);
pub_key = (char*)malloc(pub_len + 1);
BIO_read(pri, pri_key, pri_len);
BIO_read(pub, pub_key, pub_len);
pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';
std::cout << "Creating server socket ... ";
acc = BIO_new_accept("*:5055");
if (!acc)
int_error("Error creating server socket");
std::cout << "done\n";
std::cout << "Binding server socket ... ";
if (BIO_do_accept(acc) <= 0)
int_error("Error binding server socket");
std::cout << "done\n";
while (true) {
std::cout << "Accepting connections ...\n";
if (BIO_do_accept(acc) <= 0)
int_error("Error accepting connection");
client = BIO_pop(acc);
std::cout << "Creating context ... ";
if (!(ssl = SSL_new(ctx)))
int_error("Error creating SSL context");
std::cout << "done\n";
SSL_set_bio(ssl, client, client);
if (SSL_accept(ssl) <= 0)
int_error("Error accepting SSL connection");
std::cout << "SSL connection opened: " << SSL_get_cipher(ssl) << " " <<
SSL_get_cipher_version(ssl) << " (" << SSL_get_cipher_bits(ssl, 0) << " bits)\n";
char buff[256] = {0};
int r = SSL_read(ssl, buff, sizeof buff);
if (r > 0) {
std::cout << buff;
SSL_write(ssl, keypair, 1024 );
}
SSL_shutdown(ssl);
SSL_free(ssl);
std::cout << "SSL connection finished\n";
}
SSL_CTX_free(ctx);
BIO_free(acc);
std::cout << "Server closed\n";
}
Here is my client code:
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <openssl/ssl.h>
#include <openssl/err.h>
using namespace std;
using std::exit;
#define int_error(msg) handle_error(__FILE__, __LINE__, msg)
void handle_error(const char* file, int lineno, const char* msg)
{
std::cerr << "** " << file << ":" << lineno << " " << msg << "\n";
ERR_print_errors_fp(stderr);
exit(-1);
}
void init_OpenSSL()
{
std::cout << "Initializng OpenSSL library ... ";
if (!SSL_library_init())
int_error("OpenSSL initialization failed");
std::cout << "done\n";
SSL_load_error_strings();
}
SSL_CTX* setup_ctx()
{
SSL_CTX* ctx;
std::cout << "Creating context ... ";
ctx = SSL_CTX_new(TLSv1_client_method());
if (!ctx)
int_error("SSL_CTX_new failed");
std::cout << "done\n";
std::cout << "Setting cipher list ... ";
if (SSL_CTX_set_cipher_list(ctx, "ADH-AES256-SHA") != 1)
int_error("Error setting cipher list (no valid ciphers)");
std::cout << "done\n";
return ctx;
}
int main()
{
init_OpenSSL();
BIO* conn;
SSL* ssl;
SSL_CTX* ctx;
ofstream myfile;
ctx = setup_ctx();
std::cout << "Creating connection ... ";
conn = BIO_new_connect("192.168.1.10:5055");
if (!conn)
int_error("Error creating connection");
std::cout << "done\n";
std::cout << "Connecting to server ... ";
if (BIO_do_connect(conn) <= 0)
int_error("Error connecting to server");
std::cout << "done\n";
std::cout << "Creating context ... ";
if (!(ssl = SSL_new(ctx)))
int_error("Error creating an SSL context");
std::cout << "done\n";
SSL_set_bio(ssl, conn, conn);
std::cout << "Opening connection ... ";
if (SSL_connect(ssl) <= 0)
int_error("Error connecting SSL object");
std::cout << "done\n";
SSL_write(ssl, "The client is connected", 26);
char buff[64] = {0};
int bread = SSL_read(ssl, buff, sizeof buff);
if (bread > 0)
std::cout << "The key has been recieved\n";
myfile.open ("keypair.pem");
myfile << buff;
myfile.close();
SSL_shutdown(ssl);
SSL_free(ssl);
std::cout << "SSL connection finished\n";
SSL_CTX_free(ctx);
std::cout << "Client finished\n";
}
Can someone show me what i did wrong and it would be great if someone can tell me how i can get my private key and public keys(server generated) separately. Thanks a lot guys...really appreciate it