Ok, so I’m able to create a listening socket in my Android App using the following code:
bool CSocket::tcplisten(int port, int max, int mode)
{
if((sockid = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) return false;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
if(mode)setsync(1);
if(bind(sockid, (struct sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)
{
closesocket(sockid);
return false;
}
if(listen(sockid, max) == SOCKET_ERROR)
{
closesocket(sockid);
return false;
}
return true;
}
I am then able to connect to it in the SAME process using the following code:
bool CSocket::tcpconnect(char *address, int port, int mode)
{
sockaddr_in addr;
hostent* hostEntry;
if((sockid = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
return false;
if((hostEntry = gethostbyname(address)) == NULL)
{
closesocket(sockid);
return false;
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons((u_short)port);
if(mode ==2)setsync(1);
if(connect(sockid, (struct sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)
{
closesocket(sockid);
return false;
}
if(mode ==1)setsync(1);
return true;
}
The problem is, I am unable to connect to other machines running a listening socket or on remote machines like google.com. Any ideas why I can’t get it to work?
After some tweaking and probing, I found that the error occurs at the line:
if(connect(sockid, (struct sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)
{
closesocket(sockid);
return false;
}
The errno is 111 ERCONNREFUSED… Please. ANY help would be appreciated. The application has full Internet access set in the permissions…. Any ideas?
I have the same issues with my Linux build compiled with the same code…
You are trying to connect to INADDR_ANY. You want to copy the relevant part of the hostent into addr.sin_addr.s_addr.