(Obvious beginner in c++, keep struggling with pointers)
I've been trying to get the IP address of the client as the server (using TCP), and to save it using a pointer to be able to re-use it later.
In a previous function, I accept the connection and save the Socket as m_clientSocket
and the Socket information in a struct sockaddr
called clientaddr
.
Now, I want the next function to return the client socket and to save the source IP, but the program keeps crashing.
In this last version, I've tried to use a pointer but there's an error in conversion that I can't fix despite my researches.
char clientIPaddr[30];
sockaddr_in clientaddr;
SOCKET m_clientSocket;
Function code
SOCKET CmTcpListener::getNewSocket(SOCKET *hSocket, char* ptrSourceIp)
{
cout << "Retrieving socket..." << endl;
if (m_newClientConnection)
{
hSocket = &m_clientSocket;
strcpy(clientIPaddr, inet_ntoa(clientaddr.sin_addr));
ptrSourceIp = &clientIPaddr;
cout << "Socket : OK" << endl;
return *hSocket;
}
else {
cout << "No new client connection." << endl;
return false;
}
}
Error
c:\work\2015\tcptransport\cmtcplistener.cpp(112) : error C2440: '=' : cannot convert from 'char (*)[30]' to 'char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
I'm assuming the rest of the code isn't necessary but if needed I'll be quick to provide it
The culprit is the line
ptrSourceIp = &clientIPaddr;
clientIPaddr
is of type char[30]
, so the type of &clientIPaddr
is char(*)[30]
, i.e. pointer to array of 30 chars. Remove the &
and you'll be OK, as the name of the array is itself a pointer to its first element (technically, arrays decay to pointers)
ptrSourceIp = clientIPaddr;
However, right now, you're not doing anything with ptrSourceIp
, at the end of the function will be unchanged since it is passed by value like any other variable. If you want to modify the passed pointer ptrSourceIp
, then you need to pass a pointer to it (i.e. a pointer-to-pointer-to-char), so the prototype of your function should be:
SOCKET CmTcpListener::getNewSocket(SOCKET *hSocket, char** ptrSourceIp)
The second argument you pass has to be &your_passed_ptr_to_char
. Inside your function you can now modify the passed pointer like
*ptrSourceIp = clientIpAddr; // now we modify it