This question already has answers here:
Default constructor with empty brackets
(9 answers)
Closed 4 years ago.
I'm new to C++ and this is my first time with its classes and I was wondering, how do I call a constructor? I've read some documentation on classes in C++ and that's how I came up with what I have. The constructor calls private methods to setup the server.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sstream>
#include <string>
#include "SimpleIni.h"
#include "MySQL.cpp"
#include <thread>
class LoginServer {
int resSocket;
MySQL mysql;
struct sockaddr_in strctAddr;
private:
void log(std::string strText, std::string strType = "INFO"){
time_t rawtime;
struct tm * timeinfo;
char buffer[50];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 50, "%c",timeinfo);
std::cout << "[" << buffer << "][" << strType << "] > " << strText << std::endl;
}
void error(std::string strError){
log(strError, "ERROR");
exit(1);
}
int setup(int intPort){
std::stringstream objStringStream;
objStringStream << intPort;
log("Initializing socket server");
resSocket = socket(AF_INET, SOCK_STREAM, 0);
if(resSocket < 0) error("Could not create socket.");
bzero((char *) &strctAddr, sizeof(strctAddr));
strctAddr.sin_family = AF_INET;
strctAddr.sin_addr.s_addr = INADDR_ANY;
strctAddr.sin_port = htons(intPort);
setsockopt(resSocket, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *) &strctAddr, sizeof(strctAddr));
if(bind(resSocket, (struct sockaddr *) &strctAddr, sizeof(strctAddr)) < 0)
error("Could not bind");
listen(resSocket, 5);
log("Listening for clients on " + objStringStream.str(), "FINE");
return 1;
}
int sendPacket(int resSock, std::string strData){
int intWrite;
char chBuffer[8192];
strcpy(chBuffer, strData.c_str());
log("Sending packet: " + strData, "SEND");
intWrite = write(resSock, chBuffer, strlen(chBuffer) + 1);
return intWrite;
}
std::string RandomString(int len){
srand(time(0));
std::string str = "`~!##$%^&*()-=_+[]\{]|;:'\",<.>/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int pos;
int size = str.size();
while(size != len) {
pos = ((rand() % (str.size() - 1)));
str.erase (pos, 1);
}
return str;
}
void handleData(int resSock, char* strData){
char * chData;
chData = strtok(strData, "\0");
while(chData != NULL){
std::string strPacket = chData;
log("Received data: " + std::string(strPacket), "RECV");
if(strPacket.compare("<policy-file-request/>") == 0){
log("Policy request received");
sendPacket(resSock, "<cross-domain-policy><allow-access-from domain='*' to-ports='6112'/></cross-domain-policy>");
} else if(strPacket.compare("<msg t='sys'><body action='verChk' r='0'><ver v='153' /></body></msg>") == 0){
log("Version check received");
sendPacket(resSock, "<msg t='sys'><body action='apiOK' r='0'></body></msg>");
}
chData = strtok(NULL, "\0");
}
}
void handleClient(int resSock){
char chBuffer[6486];
int intRead;
for(;;){
bzero(chBuffer, 6486);
intRead = read(resSock, chBuffer, 6486);
if(chBuffer == NULL) continue;
if(intRead <= 0){
log("Client disconnected");
close(resSock);
break;
} else {
handleData(resSock, chBuffer);
}
}
}
void listenToClients(){
for(;;){
std::stringstream objStringStream;
struct sockaddr_in clntAddr;
socklen_t intClients = sizeof(clntAddr);
int resClient = accept(resSocket, (struct sockaddr *) &clntAddr, &intClients);
if(resClient < 0) log("Failed to accept client", "ERROR");
setsockopt(resClient, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *) &clntAddr, sizeof(clntAddr));
char floatIP[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &clntAddr.sin_addr, floatIP, sizeof floatIP);
objStringStream << floatIP;
log("New client connected (IP: " + objStringStream.str() + ")");
std::thread objThread(&LoginServer::handleClient, this, resClient);
objThread.detach();
}
}
public:
LoginServer();
};
LoginServer::LoginServer(){
CSimpleIniA objIniParser;
objIniParser.LoadFile("Settings.conf");
#define Host objIniParser.GetValue("Database", "Host", NULL)
#define User objIniParser.GetValue("Database", "User", NULL)
#define Pass objIniParser.GetValue("Database", "Pass", NULL)
#define Name objIniParser.GetValue("Database", "Name", NULL)
if(!mysql.connect(Host, User, Pass, Name)) error("Could not establish database connection.");
setup(6112);
listenToClients();
}
int main(){
LoginServer objLoginServer();
return 0;
}
Due to the rules of parsing in C++:
LoginServer objLoginServer();
doesn't declare an object of type LoginServer. In fact is declares a function that takes no parameters and returns a LoginServer object by value.
Instead you want to say:
LoginServer objLoginServer;
Try removing the parentheses:
LoginServer objLoginServer;
If you are curious of what's going on, search for the "most vexing parse".
The constructor should be called everytime you instantiate an object, such as the line LoginServer objLoginServer; (hint: try w/o the parenthesis) or LoginServer *objLoginServer = new LoginServer();, of course remember to call delete objLoginServer; when done with it.
There are multiple ways of calling the constructor, but I guess your specific problem is that your put brackets when calling default constructor, you need to omit them: LoginServer objLoginServer;
Such problem happens because compiler isn't able to distingush between declaring function prototype and calling default constructor. Look at A B(), out of context it may be creating object with name B of type A using default constructor, or function B returning an instance of type A.
http://www.cplusplus.com/doc/tutorial/classes/
Reading this is good start. Best of luck.
Important: Notice how if we declare a new object and we want to use its default constructor (the one without parameters), we do not include parentheses ():
CRectangle rectb; // right
CRectangle rectb(); // wrong!
Related
I'm actually having troubles with a simple program which is supposed to pass a struct through named pipes.
Here is my main.cpp:
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <string>
#include "NamedPipe.hh"
int main()
{
pid_t pid;
std::string str("test_namedPipe");
NamedPipe pipe(str);
message *msg;
//Initialisation of my struct
msg = (message *)malloc(sizeof(message) + sizeof(char) * 12);
msg->type = 1;
sprintf(msg->str, "Hello World");
//Forking
pid = fork();
if (pid != 0) {
pipe.send(msg);
} else {
message msg_receive = pipe.receive(); //Here is the overflow
std::cout << "type: " << msg_receive.type << " file: " << msg_receive.str << std::endl;
}
return (0);
}
My NamedPipe.cpp:
#include "NamedPipe.hh"
#include <stdio.h>
NamedPipe::NamedPipe(std::string const &_name) : name("/tmp/" + _name) {
mkfifo(name.c_str(), 0666);
// std::cout << "create fifo " << name << std::endl;
}
NamedPipe::~NamedPipe() {
unlink(name.c_str());
}
void NamedPipe::send(message *msg) {
int fd;
int size = sizeof(char) * 12 + sizeof(message);
fd = open(name.c_str(), O_WRONLY);
write(fd, &size, sizeof(int));
write(fd, msg, (size_t)size);
close(fd);
}
message NamedPipe::receive() {
int fd;
int size;
message msg;
fd = open(name.c_str(), O_RDONLY);
read(fd, &size, sizeof(int));
read(fd, &msg, (size_t)size);
close(fd);
return (msg); //I debugged with printf. This actually reach this point before overflow
}
And my struct is defined like:
struct message {
int type;
char str[0];
};
I actually think that may be a problem of memory allocation, but I have really no idea of what I should do to fix this.
Thanks for reading/helping !
This is the root of your problem, your struct message:
char str[0];
This is not kosher in C++ (nor is the way you're using it kosher in C). When you allocate a message on the stack, you're allocating room for one int and 0 chars. Then in this line
read(fd, &msg, (size_t)size);
you write beyond your stack allocation into neverland. Then you return your message object which would be just one int in size.
Change your struct to this, and it should "work"
struct message
{
int type;
char str[ 16 ];
};
I have been working on a project and boy oh boy does my head hurt on this one. I am using a networking library called "enet" and I am trying to assign the client who connects information. Using the tutorial on the site, I use: server.event.packet->data = "client info"; However, enet complains that the string is not an "unsigned char *". Here is the build log (using clang++ to compile):
./network.h:9:14: warning: in-class initialization of non-static data member accepted as a C++11 extension
[-Wc++11-extensions]
int clients = 0;
^
main.cpp:142:28: error: assigning to 'enet_uint8 *' (aka 'unsigned char *') from incompatible type
'const char [12]';
server.event.packet->data = "client info";
^ ~~~~~~~~~~~~~
I have tried every type of casting I can think of and that I have searched for, but nothing seems to work. I can't make the darn thing happy.
Main.cpp:
#include <iostream>
#include <string>
#include <sstream>
#include <istream>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <stdio.h>
#include "network.h"
#include "clients.h"
#include "config.h"
void runCommand(std::string command);
int startNetwork();
void shutdownNetwork();
void addClientRecord();
std::string getUsername();
std::string username;
bool manualInput = false;
bool debug = true;
int iPeerCount = 0;
Server server;
int main(int argc, char ** argv){
std::string currentCommand;
if(manualInput==true){
std::cout << "Please type a command: ";
std::getline(std::cin,currentCommand);
if(debug == true){
std::cout << currentCommand << std::endl;
}
runCommand(currentCommand);
}
startNetwork();
atexit(shutdownNetwork);
return 0;
}
int startNetwork(){
if (enet_initialize () != 0){
std::cout << "\nAn error has occured while initializing ENet.\n";
return EXIT_FAILURE;
}
server.startServer();
return 1;
}
void shutdownNetwork(){
enet_deinitialize();
}
int Server::startServer(){
// server.serverOne = enet_host_create (& server.address, 32, 2, 0, 0);
// if(CUSTOM_HOST == true){
// enet_address_set_host(&address, HOST);
// } else {
server.address.host = ENET_HOST_ANY;
// }
server.address.port = PORT;
server.serverOne = enet_host_create( & server.address, 32, 2, 0, 0);
if(debug==true){
printf("[NETWORK] Host: %x \n[NETWORK] Port: %u\n", server.address.host, address.port);
}
if(server.serverOne==NULL){
std::cout << "\nAn error has occured while starting the ENet server.\n";
exit (EXIT_FAILURE);
}
monitor();
return 1;
}
void Server::monitor(){
int clients = 0;
if(debug==true){
printf( "[NETWORK] Waiting for commands...\n" );
}
printf("[NETWORK] Server online, awaiting commands and/or connections...\n");
scan_network:
while(enet_host_service (serverOne, & event, 1000) > 0){
switch(event.type){
case ENET_EVENT_TYPE_CONNECT:
clients++;
printf("[INFO] New connection from: %x:%u.\n", event.peer -> address.host, event.peer -> address.port);
addClientRecord();
/* for(int x=0;x<32;x++){
if(clients[x].name != ""){ }
else{
clients[x].name = "full";
}
}*/
break;
case ENET_EVENT_TYPE_RECEIVE:
if(debug==true){ printf("A packet of length %lu containing %s was received from %s on channel %u.\n", event.packet -> dataLength, event.packet -> data, event.peer -> data, event.channelID); }
runCommand(reinterpret_cast<const char*>(event.packet -> data));
enet_packet_destroy(event.packet);
/* printf("Disconnect client %s ? ", event.peer -> data);
gets(buffer);
std::cout<<buffer<<std::endl;
if(buffer=="yes"){
enet_peer_disconnect(event.peer, 0);
}*/ //Do not use until fixed or spam!
break;
case ENET_EVENT_TYPE_DISCONNECT:
clients--;
printf("%s disconnected.\n", event.peer -> data);
event.peer -> data = NULL;
case ENET_EVENT_TYPE_NONE:
break;
}
}
goto scan_network;
}
void runCommand(std::string command){
if((command == "disconnect") || (command == "Disconnect") || (command=="DISCONNECT")){
enet_peer_disconnect(server.event.peer,0);
printf("[INFO] Client %s issued the disconnect command.\n", server.event.peer -> data);
}
}
std::string getUsername(){
return username;
}
void addClientRecord(){
std::string bufferName = ("client " + server.clients);
server.event.packet->data = "client info";
}
Network.h:
#include <enet/enet.h>
class Server {
public:
ENetAddress address;
ENetHost * serverOne;
ENetEvent event;
int clients = 0;
int startServer();
void monitor();
};
Any ideas and help is appreciated greatly. Cheers!
As far as I can see server is a struct of type Server, its field event is ENetEvent, and its field packet is of type _ENetPacket* and its field data is a unsigned char*. So now what is hapening: you create a сstring on the stack, then assign address of the first element to the data field of global object, then you leave the function and pointer is still alive while data stored there is no longer avaliable. That is why you get segfault when using correct typecast to unsigned char*.
So you should do the following:
void addClientRecord()
{
std::string bufferName = ("client " + server.clients);
char* clientName = "client info";
// Allocate mem
char* data = new unsigned char[strlen(clientName)];
// Copy string there
strcpy(data, clientName);
// Store pointer
server.event.packet->data = (unsigned char*)data;
}
and do no not forget to clear that allocated mem. That is for you should always check if server.event.packet->data contains non-nullptr value and if it does - delete and only then assign. And you should provide a destructor for Server where it will delete that string if any present and constructor to write there a nullptr on start so you won't delete some trash address, which most certainly will lead to crash. But first of all you need to figure out whether _ENetPacket or ENetEvent classes provide any functionality for data mentioned above. This is how cstrings work.
P.S. There should be a compiler flag that will toggle char to be unsigned by default.
I'm writing code for a gateway (aka router), using boost, C++, Codeblocks on a Linux device running Debian 7.1. I'm stuck with an annoying boost bind error and I simply cannot figure out what the problem is. I have been able to print out the MAC Header before I started creating threads
Here's a my code:
#include <errno.h>
#include <sys/ioctl.h>
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <iostream>
#include <features.h>
#include <stdlib.h>
using namespace std;
int CreateRawSocket(int protocol_to_sniff)
{
int s;
if((s = socket(AF_PACKET, SOCK_RAW, htons(protocol_to_sniff))) == -1)
{
perror("Error creating raw socket");
exit(-1);
}
return s;
}
int BindRawSocketToInterface(char *device, int raw, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));
strncpy((char *)ifr.ifr_name, device, IFNAMSIZ);
if((ioctl(raw, SIOCGIFINDEX, &ifr)) == -1)
{
printf("Error getting interface index!\n");
exit(-1);
}
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);
if((bind(raw, (struct sockaddr *)&sll, sizeof(sll))) == -1)
{
perror("Error binding raw socket to interface\n");
exit(-1);
}
return 1;
}
int rawpacket_recv(int s, unsigned char *packet, int length)
{
int to_recv = 0;
to_recv = read(s, packet, length);
if(to_recv == -1)
{
perror("Error receiving packet");
exit(-1);
}
return to_recv;
}
int PrintPacketMACHdr(unsigned char *eth_packet)
{
unsigned char *ethhead;
int j;
ethhead = eth_packet;
printf("---Start of Ethernet header---");
printf("\nDestination address:\n");
for(j = 0; j < 6; j++)
{
printf("%02x:", *(ethhead+j)); //destination address (0 to 6 bit)
}
printf("\nSource address:\n");
for(j = 6; j < 12; j++)
{
printf("%02x:", *(ethhead+j)); //source address
}
printf("\nEther protocol number:\n");
for(j = 12; j < 14; j++)
{
printf("%02x", *(ethhead+j)); //protocol number
}
printf("\n---End of Ethernet header---\n");
if(*(ethhead + 12) == 8 && *(ethhead + 13) == 0)
{
return 1; //IP packet
}
if(*(ethhead + 12) == 8 && *(ethhead + 13) == 6)
{
return 2; //ARP packet
}
return 0;
}
int CreateAndBindSocket(int protocol_to_sniff, int *socket, char *interface)
{
int ethSocket = *socket; //eth1recv;
ethSocket = CreateRawSocket(protocol_to_sniff);
BindRawSocketToInterface(interface, ethSocket, ETH_P_ALL);
return ethSocket;
}
void RecvThread(int *socket) //thread function for receiving packets
{
int counter;
unsigned char *eth_buffer;
int eth_receiver;
int eth_socket = *socket
eth_buffer = (unsigned char *)malloc(ETH_P_ALL);
eth_receiver = rawpacket_recv(eth_socket, eth_buffer, ETH_P_ALL);
for(;;)
{
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try
{
//Sleep and check for interrupt();
//boost::this_thread::sleep(boost::posix_time::milliseconds(500));
usleep(50000);
PrintPacketMACHdr(eth_buffer);
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main(int argc, char **argv)
{
int eth0socket, eth1socket;
char eth0[] = "eth0";
char eth1[] = "eth1";
eth0socket = CreateAndBindSocket(ETH_P_ALL, ð0socket, eth0);
eth1socket = CreateAndBindSocket(ETH_P_ALL, ð1socket, eth1);
boost::thread eth0recvthread(RecvThread, ð0socket); //instantiate thread in main
char ch;
cin.get(ch);
eth0recvthread.interrupt();
eth0recvthread.join();
return 0;
}
Right now I'm trying to create a thread that listens on one of the sockets and (for now) prints the MAC Header of the Ethernet frame. Later I will have to save the packet in some sort of array and then make another thread that handles the packets in this array. But as the headline says, I'm getting a boost error:
/home/thomas/Workspace/minisniffer/main.cpp||In function ‘void RecvThread(int)’:|
/home/thomas/Workspace/minisniffer/main.cpp|181|warning: variable ‘eth_receiver’ set but not used [-Wunused-but-set-variable]|
../../../../usr/local/boost_1_54_0/boost/bind/bind_template.hpp|20| required from ‘boost::_bi::bind_t<R, F, L>::result_type boost::_bi::bind_t<R, F, L>::operator()() [with R = void; F = void (*)(int); L = boost::_bi::list1<boost::_bi::value<int*> >; boost::_bi::bind_t<R, F, L>::result_type = void]’|
../../../../usr/local/boost_1_54_0/boost/thread/detail/thread.hpp|117| required from ‘void boost::detail::thread_data<F>::run() [with F = boost::_bi::bind_t<void, void (*)(int), boost::_bi::list1<boost::_bi::value<int*> > >]’|
/home/thomas/Workspace/minisniffer/main.cpp|306| required from here|
../../../../usr/local/boost_1_54_0/boost/bind/bind.hpp|253|error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|222|warning: ‘boost::system::posix_category’ defined but not used [-Wunused-variable]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|223|warning: ‘boost::system::errno_ecat’ defined but not used [-Wunused-variable]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|224|warning: ‘boost::system::native_ecat’ defined but not used [-Wunused-variable]|
||=== Build finished: 4 errors, 4 warnings ===|
Tbh I have no idea what's failing, but then again I'm pretty new to C++ and Boost.
The creating and binding of sockets works just fine as they have been tested already, but the thread function RecvThread() is the one that fails me.
If someone has some idea to what I'm doing wrong (could easily be a pointer (*) or address (&) that is messing everything up) I would be so thankful!!
Thanks in advance!
I am building a client that:
Should be able to recieve information from both the server and the standart input
Should be able to recieve information from the server without asking, for example when another client sends a message.
To do so I tried using select to monitor both possible inputs.
What happens is that when a keyboard input is monitored I send a message to the client and I expect one back, so there's no problem. But when the server sends an unexpected message nothing happens, and I don't know why. Is using select() the proper way to do so? Is it even possible to use select() without listen()ing?
Here's my code (compileable):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstring>
#include <arpa/inet.h>
#include <iostream>
#include <fstream>
#define MAX_CLIENT_NAME 30
#define MAX_TWIT_SIZE 140
#define NUM_OF_ARG 4
#define ERROR -1
#define GREAT_SUCCESS 0
#define OK "OK"
#define EXIT "EXIT"
using std::string;
using std::cerr;
using std::endl;
using std::cout;
string clientName;
int srverfd, numbytes, status, maxSock ;
fd_set inputFdSet; /* Socket file descriptors we want to wake
up for, using select() */
int establishConnection(char * serverAddress,char * port){
if ((srverfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
return ERROR;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
inet_aton(serverAddress, &server.sin_addr);
server.sin_port = htons(atoi(port));
memset(&(server.sin_zero), '\0', 8);
if (connect(srverfd,(const struct sockaddr *)&server,sizeof(struct sockaddr)) == -1) {
perror("connect");
close(srverfd);
return ERROR;
}
maxSock = srverfd;
return GREAT_SUCCESS;
}
const char * getUserTweet(){
string temp;
getline(std::cin,temp);
return temp.c_str();
}
void sendMessage(string message){
if ((numbytes = send(srverfd, message.c_str(), message.length(), 0)) == -1) {
perror("sendMessage");
close(srverfd);
}
cout<<"Message sent: "<< message << endl;
return;
}
const char * getMessage(){
char buf[MAX_TWIT_SIZE];
memset(buf,'\0',MAX_TWIT_SIZE);
if ((numbytes = recv(srverfd, buf, 140, 0)) == -1) {
perror("getMessage");
close(srverfd);
}
string temp = buf;
return temp.c_str();
}
void build_select_list() {
FD_ZERO(&inputFdSet);
FD_SET(srverfd,&inputFdSet);
FD_SET(STDIN_FILENO,&inputFdSet);
if (STDIN_FILENO > maxSock)
maxSock = STDIN_FILENO;
return;
}
void readSocket(fd_set tempfd) {
const char * tweet, * inMessage;
if (FD_ISSET(srverfd,&tempfd)) {
inMessage = getMessage();
cout << inMessage << endl;
}
if (FD_ISSET(STDIN_FILENO,&tempfd)) {
tweet = getUserTweet();
sendMessage(tweet);
inMessage = getMessage();
if (strcmp(inMessage,OK) != 0) {
cout << inMessage << endl;
}
if (strcmp(inMessage,EXIT) == 0) {
return;
}
}
return;
}
int main (int argc, char *argv[] ){
int value;
bool clientON = false;
if(establishConnection(argv[2],argv[3])){
cerr << "usage: failed to make connection" << endl << "exiting..." << endl;
exit(EXIT_FAILURE);
}
cout << "Connected successfully" << endl;
sendMessage("CONNECT "+clientName); //Connect
if(strcmp(getMessage(),OK) == 0){
clientON = true;
}
while(clientON){
build_select_list();
value = select(maxSock, &inputFdSet, NULL, NULL, NULL);
if (value < 0) {
perror("select");
exit(EXIT_FAILURE);
}
if (value == 0) {
continue;
}
else {
readSocket(inputFdSet);
}
}
sendMessage("DISCONNECT");
if(strcmp(getMessage(),OK) == 0){
// do nothing
}
close(srverfd);
return 0;
}
Your select call is invalid. The first parameter must be the highest file descriptor in any of the sets, plus one.
As you have it, an event on srverfd will not "wake up" the select call (unless STDIN_FILENO was somehow less than srverfd, in which case stdin events wouldn't unlock select - but that won't happen in practice).
There are quite a few other problems with your code. (It doesn't really look like C++.)
getUserTweet is unreliable (undefined behavior - temp is destroyed as soon as the function returns, so the char* you return has disappeared by the time its caller will try to use it). Same for getMessage. To remedy that, use std::string everywhere, and only extract the char* when you call into C library functions).
readSocket needlessly copies the FD set (can be expensive).
You should really get rid of all those globals - build one or two classes to encapsulate that state and the networking functions, or something like that.
I'm writing a sniffer class with c++ as following code.
#include "Capture.h"
#include <sys/socket.h>
#include <cstring>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <pthread.h>
Capture::Capture(int sniff_socket): sniff_socket_(sniff_socket), sniff_threadID_(0)
{
}
bool Capture::endCapture()
{
if(!sniff_threadID_)
return false;
cout << "Asking capture thread to stop\n" <<endl;
return !pthread_cancel(sniff_threadID_);
}
bool Capture::startCapture()
{
if(pthread_create(&sniff_threadID_, NULL, Capture::sniffer_thread, NULL)) {
cerr << "Unable to create capture thread"<<endl;
return false;
}
return true;
}
void *Capture::sniffer_thread(void *)
{
int MTU = 2048;
char buffer[MTU];
ssize_t msg_len;
struct iphdr *ip_header;
struct ethhdr *eth_header;
struct tcphdr *tcp_header;
void *packet;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
while (1) {
msg_len = recvfrom(sniff_socket_, buffer, MTU, 0, NULL, NULL);
eth_header = (struct ethhdr*)buffer;
ip_header = (iphdr*)(buffer + sizeof(ethhdr));
tcp_header = (struct tcphdr*)(buffer + sizeof(struct ethhdr) + sizeof(struct iphdr));
if(msg_len != -1){
packet = malloc(msg_len);
memcpy(packet, buffer, msg_len);
pthread_testcancel();
//queue add should be here
} else {
cerr<<"Error capture thread recvfrom"<<endl;
pthread_exit(NULL);
}
}
return NULL;
}
Capture::~Capture()
{
// TODO Auto-generated destructor stub
}
However, when I compiled the code, g++ said that
../Capture.cpp: In member function ‘bool Capture::startCapture()’:
../Capture.cpp:30: error: argument of type ‘void* (Capture::)(void*)’ does not match ‘void* (*)(void*)’
Could somebody help me out of this problem?
A member function in C++ class passes this as hidden parameter, the C function pthread_create cannot understand what this is, Since static member functions dont pass this you can use a static function like this:
class Capture
{
public:
static void *sniffer_thread(void*);
};
pthread_create(..., Capture::sniffer_thread, NULL);
First of all: is Capture::sniffer_thread static? cause a member function pointer is not a function pointer! These two kinds of pointers are incompatible!