Good afternoon,
I'm at my wits end. I'm keeping track of a vector of 2 IP addresses. I do a function to send them all a message via TCP. Then when I go back and check right after I send the message, the first element of the vector is changed to the second, and they are both the same!
This is where I iterate and send message to all the addresses:
vector<const char*>::battleList;
vector<const char*>::iterator it;
for(it = battleList.begin(); it !=battleList.end(); it++)
{
Message m;
cout<<"IP: "<<*it<<endl;
messenger.sendMessage(m, *it);
}
Here's the messenger function:
void Messenger::sendMessage(Message m, const char* host)
{
int n, sockfd;
struct sockaddr_in serv_addr;
struct hostent *server = gethostbyname(host);
string m1 = string(m.code) + "#";
string m2 = m.message;
string m3 = m1 + m2;
const char* buffer1 = m3.c_str();
char buffer[256];
memcpy(buffer, buffer1, sizeof(buffer1));
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
cout<<"ERROR opening socket"<<endl;
int t;
cin>>t;
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(9000);
if (connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
cout<<"ERROR connecting"<<endl;
n = write(sockfd,buffer,strlen(buffer));
n = send(sockfd, buffer, strlen(buffer), 0);
if (n < 0)
cout<<"ERROR writing to socket"<<endl;
}
As you can see, nowhere in the messaging code did I change the host address. In fact, if I put in a cout statement in the for loop, right after the message is sent, it says that the address has not been changed.
But if I do:
cout<<battleList[0]<<endl;
cout<<battleList[1]<<endl;
immediately after the for loop, the first address has changed. I called that same bit of code right before the for loop to see if there was a difference.
What on earth can the problem be? No one else is accessing these pointer values. If I take the sendMessage function out of the for loop, and just output the address, there is no problem. But I don't see the problem in sendMessage, and in fact, if I cout the host address right at the end of that function, it still is correct. The problem seems to occur in the handoff back to my for loop.