Fetch LAN ip addresses does not work - c++

The codes are as follows. I want to enumerate all the ips. Part of the codes are used to my GUI, i am sure that the error has no relevance with them.
void udpchat1::getNameAndIp() {
struct hostent *host;
struct in_addr *ptr;
DWORD dwScope = RESOURCE_CONTEXT;
NETRESOURCE *NetResource = NULL;
HANDLE hEnum;
WNetOpenEnum(dwScope, NULL, NULL, NULL, &hEnum);
WSADATA wsaData;
WSAStartup(MAKEWORD(1, 1), &wsaData);
ui.IpListWidget->clear();
names.clear();
ui.chatIpLabel->setText("1111111111111");
sendAble = false;
// flag = false;
if (hEnum)
{
DWORD Count = 0xFFFFFFFF;
DWORD BufferSize = 10240;
LPVOID Buffer = new char[10240];
WNetEnumResource(hEnum, &Count, Buffer, &BufferSize);
NetResource = (NETRESOURCE*)Buffer;
char szHostName[200];
for (unsigned int i = 0; i < BufferSize / sizeof(NETRESOURCE); i++, NetResource++)
{
if (NetResource->dwUsage == RESOURCEUSAGE_CONTAINER && NetResource->dwType == RESOURCETYPE_ANY)
{
if (NetResource->lpRemoteName)
{
CString strFullName = NetResource->lpRemoteName;
if (0 == strFullName.Left(2).Compare(_T("\\\\")))
strFullName = strFullName.Right(strFullName.GetLength() - 2);
gethostname(szHostName, strlen(szHostName));
USES_CONVERSION;
char *pchar = T2A(strFullName);
host = gethostbyname(pchar);
if (host == NULL) continue;
ptr = (struct in_addr *) host->h_addr_list[0];
std::string str = "";
for (int n = 0; n < 4; n++)
{
CString addr;
if (n > 0)
{
str += ".";
}
int value = (unsigned int)((unsigned char*)host->h_addr_list[0])[n];
char p[20];
sprintf(p, "%d", value);
str.append(p);
}
names.insert(std::pair<std::string, std::string>(host->h_name, str));
ui.IpListWidget->addItem(QString::fromStdString(host->h_name));
//std::cout << "IP:" << str << " Name:" << host->h_name << std::endl;
}
}
}
delete Buffer;
WNetCloseEnum(hEnum);
}
WSACleanup();
}
I used debugging, and i found the program can not get in to this if statement.
if (NetResource->lpRemoteName)
Here is a screenshot of the debug inspector.

Related

Shared memory is working only the first time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using shared memory to pass values between processes. It's working the first time, but when I try changing it again, the value is not getting reflected in other processes. First process A changes the value and signal B. It uses it and passes back the control to A. Then A again changes the value, but this new value is not getting reflected in process B.
// FILE 1
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/time.h>
#include<iostream>
#include<netinet/in.h>
#include<sys/select.h>
#include<sys/shm.h>
#include<signal.h>
using namespace std;
struct shm
{
int aid;
int sid;
int bid;
int cid;
int portno;
int pno;
//int ports[4];
}*val;
int ports[4];
int sfds[4];
int count = 4;
void func1(int a)
{
fd_set rfds;
while (1)
{
FD_ZERO(&rfds);
struct timeval timer;
timer.tv_sec = 0;
timer.tv_usec = 10;
for (int i = 0; i < count; i++)
{
FD_SET(sfds[i], &rfds);
}
if (select(sfds[count - 1] + 1, &rfds, NULL, NULL, &timer))
{
for (int i = 0; i < count; i++)
{
if (FD_ISSET(sfds[i], &rfds))
{
val->pno = i;
val->portno = ports[i];
cout << "port number:" << val->portno << endl;
close(sfds[i]);
// Remove the corresponding sfd
for (int j = i; j < count - 1; j++)
{
sfds[j] = sfds[j + 1];
ports[j] = ports[j + 1];
}
count--;
kill(val->aid, SIGUSR2);
if (count > 0)
signal(SIGUSR1, &func1);
else
exit(1);
return;
}
}
}
}
}
void func2(int b)
{
struct sockaddr_in cliaddr;
socklen_t clilen;
int lc = 0;
for (int i = 0; i < 1; i++)
{
int nsfd = accept(sfds[val->pno], (struct sockaddr*) &cliaddr, &clilen);
if (nsfd < 0)
{
perror("Error");
exit(1);
}
cout << "Connection accepted";
send(nsfd, "OkaA", 5, 0);
close(nsfd);
}
if (close(sfds[val->pno]) < 0)
{
perror("Error closing");
exit(1);
}
cout << "Closed" << endl;
// Remove the corresponding sfd
for (int i = val->pno; i < count - 1; i++)
{
sfds[i] = sfds[i + 1];
ports[i] = ports[i + 1];
}
count--;
cout << " val->portnumber " << val->portno << endl;
kill(val->bid, SIGUSR1);
if (count > 0)
signal(SIGUSR2, &func2);
else
exit(1);
return;
}
int main()
{
int shmid = shmget(123456, sizeof(struct shm), IPC_CREAT | 0666);
if (shmid < 0)
{
perror("Error");
}
val = (struct shm*) shmat(shmid, NULL, 0);
//cout<<"yo2";
signal(SIGUSR1, &func1);
signal(SIGUSR2, &func2);
for (int i = 0; i < 4; i++)
{
//val->ports[i] = 7590+i;
sfds[i] = socket(AF_INET, SOCK_STREAM, 0);
const int optVal = 1;
const socklen_t optLen = sizeof(optVal);
int rtn = setsockopt(sfds[i], SOL_SOCKET, SO_REUSEADDR, (void*) &optVal,
optLen);
if (rtn < 0)
{
perror("Error");
exit(1);
}
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7590 + i);
ports[i] = i;
servaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(sfds[i], (struct sockaddr*) &servaddr, sizeof(servaddr)) < 0)
{
perror("Error");
exit(1);
}
if (listen(sfds[i], 1) < 0)
{
perror("Error");
exit(1);
}
}
int c = fork();
if (c > 0)
{
val->aid = c;
val->sid = getpid();
kill(getpid(), SIGUSR1);
while (1)
;
}
else if (c == 0)
{
while (1)
;
}
else
{
perror("Error");
exit(1);
}
}
// FILE 2
#include<stdio.h>
#include<signal.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/time.h>
#include<iostream>
#include<netinet/in.h>
#include<sys/select.h>
#include<sys/shm.h>
using namespace std;
struct shm
{
int aid;
int sid;
int bid;
int cid;
int pno;
int portno;
}*val;
int sfds[4];
int count = 4;
void func1(int a)
{
int sfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7590 + val->portno);
servaddr.sin_addr.s_addr = INADDR_ANY;
const int optVal = 1;
const socklen_t optLen = sizeof(optVal);
cout << val->portno << " vpn " << endl;
int rtn = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*) &optVal,
optLen);
while (bind(sfd, (struct sockaddr*) &servaddr, sizeof(servaddr)) < 0)
{
perror("Error");
}
cout << endl << "Done" << endl;
if (listen(sfd, 1) < 0)
{
perror("Error");
exit(1);
}
for (int i = 0; i < 1; i++)
{
struct sockaddr_in cliaddr;
socklen_t clilen;
int nsfd = accept(sfd, (struct sockaddr*) &cliaddr, &clilen);
send(nsfd, "OkaB", 5, 0);
}
close(sfd);
signal(SIGUSR1, &func1);
kill(val->cid, SIGUSR1);
}
int main()
{
signal(SIGUSR1, &func1);
int shmid = shmget(123456, sizeof(struct shm), IPC_CREAT | 0666);
if (shmid < 0)
{
perror("Error");
}
val = (struct shm*) shmat(shmid, NULL, 0);
val->bid = getpid();
while (1)
;
}
The problem may come from the struct shm definition:
In file 1
struct shm
{
int aid;
int sid;
int bid;
int cid;
int portno;
int pno;
//int ports[4];
}*val;
In other file :
struct shm
{
int aid;
int sid;
int bid;
int cid;
int pno;
int portno;
}*val;
pno and portno are not at the same place.
And as LPs pointed, only one process should create the shared memory (IPC_CREAT)

How to receive the response of a server into a string variable using c++?

I'm writing a console application using c++ with sockets. I need to receive the response not into a char array but into a string. The problem is that I don't know how to do it. Someone know the answer? Thanks to all.
Now I've this code:
char buffer[1000000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 1000000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
I need to translate buffer into a string before to receive data because if I use the char array the buffer isn't enought big to store the entaire result and if I increase the size, Visuale Studio show me an error with the initialization of the socket
I use :
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
return 1;
}
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.site.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
This is the way beacuse I need to store the response into a string but: How can I do it?
ok, let's be reasonable and get rid of that ridiculously huge buffer.
char buffer[4096];
int nDataLength;
std::string result;
while ((nDataLength = recv(Socket, buffer, 4096, 0)) > 0) {
std::copy_if(buffer, buffer + nDataLength,
std::back_inserter(result),
[](char c) {
return !std::isspace(c);
// maybe you wanted this instead?
// return std::isprint(c);
});
}
// result now contains your string, without any white space
Concatenate ( join together ) a string variable with a char buffer in your loop like this:
myString+=buffer[i]; // myString = myString + buffer[i];
Example code listing:
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string myString;
locale local;
//***************************
void getWebsite(char *url );
//***************************
int main (){
getWebsite("www.google.com" );
for (size_t i=0; i<myString.length(); ++i) myString[i]= tolower(myString[i],local);
cout <<myString;
return 0;
}
//***************************
void getWebsite(char *url ){
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
char *getHttp= new char[256];
memset(getHttp,' ', sizeof(getHttp) );
strcpy(getHttp,"GET / HTTP/1.1\r\nHost: ");
strcat(getHttp,url);
strcat(getHttp,"\r\nConnection: close\r\n\r\n");
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(url);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
system("pause");
//return 1;
}
cout << "Connected.\n";
//send(Socket,"GET / HTTP/1.1\r\nHost: www.cplusplus.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"),0);
send(Socket,getHttp, strlen(getHttp),0 );
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
myString+=buffer[i]; // myString = myString + buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
delete[] getHttp;
}
Assuming the storage space is the actually issue, a chained buffer approach could be a solution.
#define MAX_BUF_LEN 10000
typedef struct netBuf
{
char data[MAX_BUF_LEN];
struct netBuf * pNext;
} NET_BUF;
NET_BUF * pHead = NULL;
NET_BUF *pCurrent = malloc(sizeof(NET_BUF));
pCurrent->pNext = NULL:
pHead = pCurrent;
char * pData = pCurrent->data;
int nDataLength;
int dataToRead = MAX_BUF_LEN;
while ((nDataLength = recv(Socket, pData, dataToRead, 0)) > 0) {
if(dataToRead == nDataLength)
{
pCurrent->pNext = malloc(sizeof(NET_BUF));
pCurrent = pCurrent->pNext;
pCurrent->pNext = NULL;
pData = pCurrent->data;
dataToRead = MAX_BUF_LEN;
}
else
{
dataToRead -= nDataLength;
pData +=nDataLength;
}
}
You can use this:
const std::ssize_t max_size = 1000000;
std::string buffer();
buffer.resize(max_size);
// and use where you need:
ssize_t new_size = recv(Socket, &buffer[0], max_size, 0);
buffer.resize (new_size);
Because std::string has no fixed size (and possibly null), you have to be sure that memory is allocated. Here, I use resize() function of std::string to be sure to have enough memory inside string. And after filling string, you have to resize manually string.
BUT recv is a plain old C function, so it simply can't resize std::string by itself!
Another solution is to allocate small char array and concatenate it to a final std::string which contains global response :
std::final final;
// retrieve small char array of max_size, for example equal to 256
final += std::string (buffer, max_size);

how to correct convert char to byte in C++

I have some problem.
I write next code.
z=recv(conn,buff,512,0);//"Hi VahagnAAAAAAA" - but encrypted for example "zЖWЙЇ%ЂАЊ"S]яАAЧ0АбЯ.Щk5S¤Oц", length 32
BYTE messageLen = (BYTE)strlen(buff);// messageLen = 32
BYTE encryptedMessage[32];
memcpy(encryptedMessage, buff, messageLen);//!!!!!!!!!!!
DWORD encryptedMessageLen = messageLen;
CryptDecrypt(hSessionKeyRSA_2,NULL,TRUE,0,encryptedMessage, &encryptedMessageLen);
cout<<encryptedMessage<<endl;
I recv to buffer char array 32 length.
Where I copy encrypted text
"zЖWЙЇ%ЂАЊ"S]яАAЧ0АбЯ.Щk5S¤Oц"
to byte array, on the encryptedMessage have next value
"zЖWЙЇ%ЂАЊ"S]яАAЧ0АбЯ.Щk5S¤OцMMMMMMMMMMMMMMMMMMM"
where I decrypted I don't get start text, I get
"Ik VqagnеAAcS]‰МММММММММММ ММММММММ"
How I can fix it? please help me.
UPDATE
Client main()
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
const char* servername="127.0.0.1";
Sleep(2000);
setlocale(LC_ALL, "Russian");
WSADATA wsaData;
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret)
return 0;
SOCKET conn;
conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(conn==INVALID_SOCKET)
return 0;
if(inet_addr(servername)==INADDR_NONE)
{
hp=gethostbyname(servername);
}
else
{
addr=inet_addr(servername);
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
closesocket(conn);
return 0;
}
server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(20248);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
closesocket(conn);
return 0;
}
std::cout<<"Connected to server";
char buff[512];
memset(buff,'\0',512);
int z;
z=recv(conn,(char*)exportRSAKey,140,0);//Import RSA key
z=recv(conn,(char*)exportAESKey,140,0);//Import AES key
z=recv(conn,buff,512,0);//Get encryption text
importKey();//import key to client
BYTE messageLen = (BYTE)strlen(buff);
BYTE encryptedMessage[33];
memcpy(encryptedMessage, buff, messageLen);
DWORD encryptedMessageLen = messageLen;
CryptDecrypt(hSessionKeyRSA_2,NULL,FALSE,0,encryptedMessage, &encryptedMessageLen);
cout<<encryptedMessage<<endl;
// buff[z]=0;
}
Import key to client
if (CryptAcquireContext(&hCryptProv_RSA_2, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
{
printf("A cryptographic provider has been acquired.\r\n");
}
else
{
DWORD d = GetLastError();
return -1;
}
int iii = CryptImportKey(hCryptProv_RSA_2,(BYTE *)&exportAESKey,140,NULL,NULL,&hSessionKeyRSA_2);
if(CryptSetKeyParam(hSessionKeyRSA_2, KP_IV, exportRSAKey, 0))
{
cout<<"ok";
}
Server main()
std::cout<<"Client connected... "<<pParam<<std::endl;
char buff[512];
CString cmd;
CString params;
int n;
int x;
BOOL auth=false;
SOCKET client=(SOCKET)pParam;
strcpy(buff,"#Server Ready.\r\n");
char keybuff[1024];
createRSAPublicKey();//create enc_dec key
//keybuff = exportRSAKey;
//memset(rec,'\0',512);
const char *p = reinterpret_cast<const char*>(exportRSAKey);
send(client,p,140,0);//send RSA
const char *pp = reinterpret_cast<const char*>(exportAESKey);
send(client,pp,140,0);//Send AES
const char *ppp = reinterpret_cast<const char*>(encryptedMessage);
send(client,ppp,512,0);//Send encrypt text
createRSAPublicKey()
BOOL createRSAPublicKey()
{
if (CryptAcquireContext(&hCryptProv_AES, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
{
printf("A cryptographic provider has been acquired.\r\n");
}
else
{
DWORD d = GetLastError();
return -1;
}
HCRYPTKEY hSessionKey_AES;
if (!CryptGenKey(hCryptProv_AES, CALG_AES_256, CRYPT_EXPORTABLE, &hSessionKey_AES))
{
DWORD d = GetLastError();
return -1;
}
// Create RSA key to encrypt AES one
HCRYPTKEY hSessionKey;
if (!CryptGenKey(hCryptProv_AES, AT_KEYEXCHANGE, 1024 << 16, &hSessionKey))
{
DWORD d = GetLastError();
return -1;
}
// Export key
DWORD keylen;
BOOL ok = CryptExportKey(hSessionKey_AES, hSessionKey, SIMPLEBLOB, 0, exportRSAKey, &keylen);
if (ok == FALSE)
{
DWORD d = GetLastError();
return -1;
}
BYTE *encKey = (BYTE *)malloc(keylen);
ok = CryptExportKey(hSessionKey_AES, hSessionKey, SIMPLEBLOB, 0, exportAESKey, &keylen);
if (ok == FALSE)
{
DWORD d = GetLastError();
return -1;
}
else
printf("A cryptographic key export succeeded.\r\n");
BYTE messageLen = (BYTE)strlen(mess);
memcpy(encryptedMessage, mess, messageLen);
DWORD encryptedMessageLen = messageLen;
CryptEncrypt(hSessionKey_AES, NULL, TRUE, 0, encryptedMessage, &encryptedMessageLen, sizeof(encryptedMessage));
}
You are using strlen() to get the length of buff, but recv() does not null-terminate the buffer unless a null terminator was actually transmitted and read. You should instead be using the return value of recv(), which is the number of bytes actually read:
z=recv(conn,buff,512,0);
messageLen = z;//(BYTE)strlen(buff);
That being said, TCP is a byte stream, it has no concept of message boundaries. There is no 1-to-1 relationship between send() and recv() in TCP, like there is in UDP, so recv() above could read as little as 1 byte or as many as 512 bytes, and buff could contain a full message, a partial message, pieces of multiple messages, etc. You can't just blindly read and expect to receive everything in one go. You need to take all of that into account.
Design your TCP protocol to delimit messages, either with a preceding header that specifies the message length, or a trailing delimiter that never appears in the message body. Call recv() as many times as it takes, buffering any received data, and only process/decrypt complete messages that are in your buffer, leaving partial message data in the buffer to be completed by later reads.
Try something more like this:
Client main()
int readBuffer(SOCKET s, void *buffer, int buflen)
{
unsigned char *pbuf = (unsigned char*) buffer;
int total = 0;
while (total < buflen)
{
int num = recv(s, pbuf+total, buflen-total, 0);
if (num < 0)
return SOCKET_ERROR;
if (num == 0)
return 0;
total += num;
}
return total;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
const char* servername="127.0.0.1";
setlocale(LC_ALL, "Russian");
WSADATA wsaData;
memset(&wsaData, 0, sizeof(wsaData));
int wsaret = WSAStartup(0x101, &wsaData);
if (wsaret != 0)
return 0;
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_addr.s_addr = inet_addr(servername);
if (server.sin_addr.s_addr == INADDR_NONE)
{
struct hostent *hp = gethostbyname(servername);
if (hp == NULL)
return 0;
server.sin_addr = *((in_addr*)hp->h_addr);
}
server.sin_family = AF_INET;
server.sin_port = htons(20248);
SOCKET conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn == INVALID_SOCKET)
return 0;
if (connect(conn, (struct sockaddr*)&server, sizeof(server)) != 0)
{
closesocket(conn);
return 0;
}
std::cout << "Connected to server";
if (readBuffer(conn, exportRSAKey, 140) <= 0) //Import RSA key
{
closesocket(conn);
return 0;
}
if (readBuffer(conn, exportAESKey, 140) <= 0) //Import AES key
{
closesocket(conn);
return 0;
}
importKey();//import key to client
DWORD messageLen;
if (readBuffer(conn, &messageLen, sizeof(messageLen)) <= 0) //Get encryption text length
{
closesocket(conn);
return 0;
}
messageLen = ntohl(messageLen);
std::vector<BYTE> buff(messageLen);
if (messageLen > 0)
{
if (readBuffer(conn, &buff[0], messageLen) <= 0) //Get encryption text
{
closesocket(conn);
return 0;
}
if (!CryptDecrypt(hSessionKeyRSA_2, NULL, FALSE, 0, &buff[0], &messageLen))
{
closesocket(conn);
return 0;
}
}
std::cout << std::string((char*)buff.data(), messageLen) << std::endl;
}
Server main()
int sendBuffer(SOCKET s, void *buffer, int buflen)
{
unsigned char *pbuf = (unsigned char*) buffer;
int total = 0;
while (total < buflen)
{
int num = send(s, pbuf+total, buflen-total, 0);
if (num < 0)
return SOCKET_ERROR;
if (num == 0)
return 0;
total += num;
}
return total;
}
...
SOCKET client = (SOCKET)pParam;
std::cout << "Client connected... " << pParam << std::endl;
...
createRSAPublicKey();//create enc_dec key
...
if (sendBuffer(client, exportRSAKey, 140) <= 0) //send RSA
{
closesocket(client);
return;
}
if (sendBuffer(client, exportAESKey, 140) <= 0) //Send AES
{
closesocket(client);
return;
}
...
DWORD tmpMessageLen = htonl(messageLen);
if (sendBuffer(client, &tmpMessageLen, sizeof(tmpMessageLen)); //Send encrypt text length
{
closesocket(client);
return;
}
if (sendBuffer(client, encryptedMessage, messageLen) <= 0) //Send encrypt text
{
closesocket(client);
return;
}
...

Sockets over NDK

When I'm connecting with a socket in NDK, as a result of the read call, I always get -1.(Error).
I was looking over the internet several times and I couldn't find a solution. Can you help me?
Here is my code.
void * SocketManager::socketCall(void *ptr) {
int socket_, n;
SocketManager *manager = (SocketManager*) ptr;
while (manager->semaph) ;
manager->semaph = true;
bool didConnect = false;
size_t bufferSize = 32000;
char buffer[bufferSize];
const char* value = manager->host.c_str();
stringstream strValue;
strValue << value;
unsigned int host;
strValue >> host;
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(10983);
inet_aton(manager->host.c_str(), &server_address.sin_addr);
socket_ = socket(AF_INET, SOCK_STREAM, 0);
if (socket_ < 0)
CCLog("ERROR ABRIENDO EL SOCKET");
n = ::connect(socket_, (struct sockaddr *) &server_address,sizeof(server_address));
if (n < 0)
close(socket_);
manager->onConnect();
didConnect = true;
while (!manager->mustDisconnect) {
n = read(socket_, &buffer, bufferSize);
if(n<=0)
break;
manager->onReadData(buffer, sizeof(buffer));
}
if (socket_) {
close(socket_);
if (didConnect)
manager->onDisconnect();
else
manager->onTimeout();
}
manager->semaph = false;
manager->mustDisconnect = false;
return 0;
}

C++ BaseAddress and entry point address

I know that in c# I can do:
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
currentProcess.Modules[0].BaseAddress
currentProcess.Modules[0].EntryPointAddress
How would I get this information in C++?
Taking a look I have:
void
get_module_name_for_address(LPVOID address,
TCHAR *buf, int buf_size)
{
HANDLE process;
HMODULE modules[256];
DWORD bytes_needed, num_modules;
unsigned int i;
buf[0] = '\0';
process = GetCurrentProcess();
if (EnumProcessModules(process, (HMODULE *) &modules,
sizeof(modules), &bytes_needed) == 0)
{
return;
}
if (bytes_needed > sizeof(modules))
bytes_needed = sizeof(modules);
num_modules = bytes_needed / sizeof(HMODULE);
for (i = 0; i < num_modules; i++)
{
MODULEINFO mi;
if (GetModuleInformation(process, modules[i], &mi, sizeof(mi)) != 0)
{
LPVOID start, end;
start = mi.lpBaseOfDll;
end = (char *) start + mi.SizeOfImage;
if (address >= start && address <= end)
{
GetModuleBaseName(process, modules[i], buf, buf_size);
return;
}
}
}
}
GetModuleInformation() in unmanaged code: http://msdn.microsoft.com/en-us/library/ms683201%28v=VS.85%29.aspx