Unable to connect to server (over a remote connection) - c++

I have been working on this project for a while and wanted to test some new features over a remote connection, but the client failed to connect (while it was able to connect in the past). Everything works fine locally. At the moment I am not able to port foward so I'm using hamachi. I have tried capturing the hamachi network traffic with wireshark, and the client requests do arrive, but the server doesn't receive them.
Any help is greatly appreciated.
Code (error checking left out to make the code more readable):
Client:
addrinfo ADDRESSINFO, *CLIENTINFO=NULL;
ZeroMemory(&ADDRESSINFO, sizeof(ADDRESSINFO));
ADDRESSINFO.ai_family = AF_INET;
ADDRESSINFO.ai_socktype = SOCK_STREAM;
ADDRESSINFO.ai_protocol = IPPROTO_TCP;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
getaddrinfo(strIP.c_str(), strPort.c_str(), &ADDRESSINFO, &CLIENTINFO);
connect(ConnectSocket, CLIENTINFO->ai_addr, CLIENTINFO->ai_addrlen);
freeaddrinfo(CLIENTINFO);
Server:
addrinfo ADDRESSINFO, *SERVERINFO=NULL;
ZeroMemory(&ADDRESSINFO, sizeof(ADDRESSINFO));
ADDRESSINFO.ai_family = AF_INET;
ADDRESSINFO.ai_socktype = SOCK_STREAM;
ADDRESSINFO.ai_protocol = IPPROTO_TCP;
getaddrinfo(SERVER_IP, SERVER_PORT, &ADDRESSINFO, &SERVERINFO);
ListenSocket = socket(SERVERINFO->ai_family, SERVERINFO->ai_socktype, SERVERINFO->ai_protocol);
ConnectionSocket = socket(SERVERINFO->ai_family, SERVERINFO->ai_socktype, SERVERINFO->ai_protocol);
bind(ListenSocket, SERVERINFO->ai_addr, SERVERINFO->ai_addrlen);
freeaddrinfo(SERVERINFO);
listen( ListenSocket, SOMAXCONN )
while(true)
{
if(ConnectionSocket = accept(ListenSocket, NULL, NULL))
{
//do stuff
}
}

I do not know how abridged the code that you've pasted is but:
1) There is no place where you set destination address
2) There is no place you set destination port
3) To which port is server trying to bind?
...so this just cannot work at all.
Moreover please do handle errors - (yes you said you've omitted them on purpose) but I bet that if server refuses connection your error handling shows that. Otherwise it connects fine but you claim otherwise. You also say:
1) 'the client failed to connect'
2) and later you say 'the client requests do arrive, but the server doesn't receive them'
If you are able to connect - you should see 3 way handshake (TCP stream connection). If not error handling and wireshark will show that. You say that client requests do arrive but your code is not sending anything (no sending code available). You also say that server does not receive them - if it connects and you send anything there is no way that your error handling shows nothing and server receives nothing (but server code lacks any receive routine call).
I think right now you cannot receive much help with that. Update your code, verify if it really works locally (you mean loopback here right?), then test 'not locally', add error handling and use wireshark on both client and server side.

Related

Setting up sockets for distributed system communication

I am writing client/server distributed instance for chat implementation. I want each instance to be capable of being server and client at the same time, so I am trying to assign both physical address (using bind, so other nodes could connect to node) and remote address (using connect, so the node could communicate with others). As far as I know this is impossible by sockets programming because bind/connect function can be used only once in a process. But if I want to send and receive messages (using sockets by send/recv functions) I don't see other possibility. Could you please tell me how to achieve mentioned above functionality (exchanging message through sockets by send/recv)? I am getting error (connect: Transport endpoint is already connected) if I try to use connect function after bind function like this:
if((*socket_handler = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
error("socket");
}
struct sockaddr_in socket_address;
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = INADDR_ANY;
socket_address.sin_port = htons(port);
if(bind(*socket_handler, (struct sockaddr*)&socket_address, sizeof(socket_address)) == -1) {
error("bind");
}
if(listen(*socket_handler, 5) == -1) {
error("listen");
}
if (port == port_to_connect) {
return;
}
// is it ok to connect that way?
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = INADDR_ANY;
socket_address.sins_port = htons(port_to_connect);
if(connect(*socket_handler, (struct sockaddr*)&socket_address, sizeof(socket_address)) == -1) {
error("connect");
} am_i_pointing_to_myself = false;
A TCP socket can either listen/accept, or it can connect, but it cannot do both.
Your application will likely need two separate threads. One thread would open a socket for listening, wait for a connection and handle that connection. The other one would makes a connection when the user requests it.
To keep things simple, the user thread that does the connection should send the user's message and close the connection, while the background listening thread should read a message from the accepted socket, display it to the user, and close the connection.
Another option is to have the application ask the user for server or client mode. For server mode, the app would listen and wait for a connection, then when it has a connection it can send back and forth over the connected socket. For client mode, it would make a connection to the server, then use the socket to communicate in both directions.
The problem is that you're using the same socket for both the listen() and the connect(). That is why you're getting that error.
You should be able to both listen and connect but you'll need a different socket for each.
What exactly are you trying to accomplish overall?
You said you need to have each instance be able to be a client or a server. That sounds like a P2P sort of thing.
Why do you need to both accept and make connections?

How to get the IP address of an incoming data packet on a DGRAM socket in WinSock2?

I am doing some work with WinSock and servers, and I want to get the IP address of the client sending a packet of information to the server.I would prefer to use SOCK_DGRAM-style sockets, using the UDP protocol. Since I am not using sockets with listen(), accept(), and connect(), and therefore cannot use getpeername(), I would like to know how I can get this information. A short code snippet would be appreciated. Also, right now I am only communicating on the server on the LAN right now, but will eventually need to move farther out.
EDIT:
As far as code goes, I'm not sure what to put.
I have a socket sock_serv
it is initialized like so:
sock_serv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
I do some recv()ing later on, after setting a timeout. I have confirmed that the timeout works, and I can get data from recv but don't know how to get the sender.
Use recvfrom(). It has an output struct sockaddr parameter. See MSDN.

Mix mode communication between IPv4 and IPv6

I have a application which acts as client and server both. As a server it accepts SOAP requests on port xxxx[Agent URL] and send notifications to the sender on port yyyy [notification URL].
So basically it acts as a server on port xxxx and client on port yyyy. My service has a dedicated IP either IPv6 or IPv4.
We are using GSOAP for communication and overriding GSOAP function tcp_connect() for client side binding.
Currently I am facing issues with transition of service to IPv6. Use case: when I listening on IPv6 address and my notification URL is IPv4...
From the GSOAP implementation a socket is created from the Notification URL.
sk = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
Now we try to bind to this socket accordingly(either IPv4 or IPv6):
struct addrinfo hints, *res, *p;
int status;
const char* client_ip = AGENT_CLIENT_IP;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if( (status=getaddrinfo(client_ip, NULL, &hints, &res))!=0 )
{
sprintf(err_msg_buf,"bind failed in tcp_connect()");
soap->fclosesocket(soap, sk);
return error;
}
for( p=res; p!=NULL; p=p->ai_next){
if(p->ai_family == AF_INET)
{
struct sockaddr_in * ipv4 = (struct sockaddr_in *)p->ai_addr;
status = bind(sk, ipv4, (int)sizeof(struct sockaddr_in));
}
else if(p->ai_family == AF_INET6)
{
struct sockaddr_in6 * ipv6 = (struct sockaddr_in6 *)p->ai_addr;
status = bind(sk, ipv6, (int)sizeof(struct sockaddr_in6));
}
else
{
sprintf(err_msg_buf,"tcp_connect() error. IP Address neither IPv6 nor IPv4 ");
soap->fclosesocket(soap, sk);
return error;
}
break;
}
if(-1 == status)
{
sprintf(err_msg_buf," Binding to client host ip failed in tcp_connect()");
return error;
}
Since the socket is already created(according to the type of Notification URL), bind fails if the socket is of type mismatch is there.
How can I make my client side binding work when socket family and agent ip address are of different family ?
Maybe I am not getting what you are trying or you have some misunderstanding of how TCP/IP and RPC normally works.
Let me paraphrase your set up and then show what I think is odd about it.
You have a server and one or multiple clients. The server accepts IPv4 and IPV6 connections on a fixed port, let us say 1337. To answer the request you open a new TCP stream (or maybe SOAP) on a different fixed port, say 1338. You are now wondering why, when a second client connects the bind to 1338 fails?
The short answer is: "The port is in use, duh, us a different port!"
But that misses the point that the setup, to say the least ODD. Although I have never used GSOAP, I have used SOAP and other RPC frameworks and what you outline is weird, unless I am missing something you did not outline.
The first thing that is odd, if you need an answer to a SOAP request, why do you simply formulate one with a return value? Call the SOAP function and the client will block until it gets an answer. If you don't want the call to block for the relatively long duration of the call do the entire thing asynchronously.
So you want to pass data to the client back later? Here you have two solutions, either the client polls the server or you open a new SOAP connection to the client. The first solution is basically desirable, because in most cases the client can connect to the server but not the other way around. For example the client can be behind a NAT, what do you do now? The second solution works well when you know that the client will always be reachable.
It seems to me that you are trying to do the second "return channel" solution. In this case why are you binding to a port? The client side of any IP connection does not need to bound to a port. The OS will automatically assign an available port. What you need to do is then bind the port on the client to a well known IP. You then use this well known client port and use it in connect on the server (or not, since you are using SOAP).
Since this is all confusing let me illustrate this with a small diagram:
Client Server
------ ------
Request Channel <random port> 1337
Back Channel 1338 <random port>
To sum up:
So either you are reimplementing something that works in SOAP and should stop doing that or if you absolutely need a back channel, simply don't call bind on a client socket.

How to listen for a server reply from broadcast?

As part of a simple networking project I'm trying to connect two computers together to send a simple data packet. The client uses a broadcast to find servers, and my server successfully detects this broadcast from the client.
The server then sends a reply packet, however I am unable to get the client to listen to the packet.
The problem seems to lie with the broadcasting method, since if I use a direct server connection, aka instead of INADDR_BROADCAST I specify the IP address 127.0.0.1 or 192.168.0.x then the server connects, sends a reply, and the client receives it.
The listening code in the client:
// Stop the client from waiting for packets if there are none.
fd_set checksockets;
checksockets.fd_count = 1;
checksockets.fd_array[0]=m_listenSocket;
struct timeval t;
t.tv_sec=0;
t.tv_usec=0;
int waiting = select(NULL, &checksockets, NULL, NULL, &t);
// If there is at least one packet receive it.
if(waiting>0) {
std::cout << "Packet received.\n";
}
From this point I attempt to find the server address with the recvfrom() method.
I've made sure to use the broadcast flag on the client socket, right after creating it. This returns no errors.
int value=true;
int result = setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof( value ) );
I've checked all possible WINSOCK functions that I've used and none return any errors.
I've also tried creating a second socket only for listening on the same port, but this conflicts with the server and therefore fails to open.
So essentially, what I'm trying to ask: How can I have a client listen for a reply from a broadcast? - aka the server address is unknown at first, I'm attempting to create a new socket using the reply address, however I'm not getting a reply address from a broadcast, despite the server receiving the broadcast and definitely sending a reply.
As you point out you won't receive any back when bound to INADDR_BROADCAST. This is normal: when you are bound to an address you only receive packets from that address. You don't need to bind the sockets to any address at all. This operation is usually required for connected sockets (i.e. TCP). If the receiving socket works I guess it is because you're doing all your tests on the same machine.
If you want to receive packets from a given address you can try to use connect or sendto and receivefrom.

How do i check the data sent to the IP Address on particular port?

I am sending data to the IP address 127.0.0.1 on port number 5152. Through socket programming i am sending the data ("Hello world") . I am receiving a acknowledgement as sent 51 Bytes. But how do i know the data received is correct or not in the above IP address.
I have created a server application , and i am using a same IP and port number here.
// Create our listening socket
//
sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sListen == SOCKET_ERROR)
{
printf("socket() failed: %d\n", WSAGetLastError());
return 1;
}
// Select the local interface and bind to it
//
if (bInterface)
{
local.sin_addr.s_addr = inet_addr(szAddress);
if (local.sin_addr.s_addr == INADDR_NONE)
usage();
}
else
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_family = AF_INET;
local.sin_port = htons(iPort);
if (bind(sListen, (struct sockaddr *)&local,
sizeof(local)) == SOCKET_ERROR)
{
printf("bind() failed: %d\n", WSAGetLastError());
return 1;
}
Bind fails with 10048 error.
Depend on what you're connecting to. If it's your application, the fact that the socket opens proves that you already have a listening socket : just display what it receives (or configure the traces on the server to display it).
Another idea when dealing with network development is to monitor actual network traffic using wireshark.
You sent your data - now you need to receive it !
You'll need to create a server that listens on port 5152 on the same box and have it display what it receives from your client.
Your error is "address already in use". That means some other program has the port open.
You can see a list of programs listening using "netstat" at the command line. Perhaps that
will help you figure it out.
Wireshark is a handy application to see what's being sent via the network. Very handy for debugging these kinds of programs.