Socket UDP- Program stops at recvfrom - c++

I try to send data via UDP from a computer to another (first Computer: Ubuntu, C++ with Eclipse, second Computer Windows 10 Matlab 2014b). The C++ computer should work as server. Sending data from C++ to Matlab works fine, but i am not able to send data in opposite direction. Every time my C++ program reaches recvfrom() it will idle at this point without doing anything anymore, even if matlab is sending data over and over againg. I tried to receive data on ubuntu via netcat while sending the packages with Matlab and that works fine as well. Even i tried something with select() but this only resulted in waiting for 10s when program reaches select() and then freezes at recvfrom again. I would be very grateful if someone can give me some help.
int Socket=socket(AF_INET, SOCK_DGRAM,0);
/*FD_ZERO(&SockSet);
FD_SET(Socket,&SockSet);
sTimeval.tv_sec=0.1;
sTimeval.tv_usec=0;
int status=select(Socket+1,&SockSet,(fd_set*)NULL,(fd_set *)NULL,&sTimeval);
cout<<status<<endl;*/
if(Socket!=-1)
cout<<"Socket created"<<endl;
else
cout<<"Socket not created"<<endl;
unsigned short port=4012;
struct in_addr serverIP;
//(void)inet_pton(AF_INET,"192.168.56.100", &clientIP);
(void)inet_pton(AF_INET,"192.168.56.101", &serverIP);
struct sockaddr_in server;
memset(&server,0, sizeof(server));
server.sin_family=AF_INET;
server.sin_addr=serverIP;
server.sin_port=htons(port);
if(bind(Socket,(struct sockaddr*)&server, sizeof(&server))!=1)
cout<<"Binding successful"<<endl;
else
cout<<"Binding failed";
struct sockaddr client;
memset(&client, 0, sizeof(client));
socklen_t clientlen=0;
struct sockaddr_in* client_in;
memset(&client_in,0,sizeof(client_in));
cout<<"warten vor recv"<<endl;
ssize_t bytesread=recvfrom(Socket, &msg, sizeof(msg), 0, &client,&clientlen);
cout<<(int)bytesread<<endl;
cout<<msg<<endl;
client_in=(struct sockaddr_in*)&client;
char* client_adr=inet_ntoa(client_in->sin_addr);
printf("%s Port%d\n", client_adr, ntohs(client_in->sin_port));
if (bytesread == -1) {
cerr << "Fehler beim empfangen" << endl;
int status = close(Socket);
if (status == 0)
cout << "Socket closed" << endl;
else if (status == -1)
cout << "Socket not closed" << endl;
return (1);
}
//Wenn Infos ueber Client nicht schon vorher aus recvfrom()
/*struct in_addr clientIP;
(void)inet_pton(AF_INET,"192.168.2.102", &clientIP);
struct sockaddr_in client;
memset(&client,0, sizeof(client));
client.sin_family=AF_INET;
client.sin_addr=clientIP;
client.sin_port=htons(portwindows);*/
char msg2[]="12345";
ssize_t bytessent=sendto(Socket,msg2,strlen(msg2),0,(struct sockaddr*)&client,sizeof(client));
cout<<(int)bytessent<< " bytes were sent"<<endl;
int status=close(Socket);
if(status==0)
cout<<"Socket closed"<<endl;
else if(status==-1)
cout<<"Socket not closed"<<endl;

After running the program in Debug mode suddenly the program is passing recvfrom, but without receiving the data which was sent. Even if i run recvfrom in a while-loop and send constantly data to the port recvfrom never get a package. If i try to run listen and accept before it (i know usally that is not necessary by udp connection) the functions both returns -1. But i can not see why my Socket is not ready to receive data. Maybe anynone have an idea to fix this problem?

Related

Non Blocking socket in C++ - Resource temporarily unavailable error

I am currently working in a server program in linux, which has to connect to a single client and has to listen to it for commands. Once it receives certain command I have to send some values in return to the client. The values are generated in the main function and the server program is run in a thread.
So, in this case I thought I have to implement non-blocking socket. But I am getting Resource temporarily unavailable error. If any anyone point me in a direction for further research it will would helpful , as I am stuck in this implementation for a long time.
Here is the while loop code,
void server::serve() {
struct sockaddr_in clientAddress;
socklen_t sin_size;
sin_size = sizeof(struct sockaddr_in);
if(client = accept(sockId,(struct sockaddr *)&clientAddress,&sin_size) == -1){
perror("accept");
}
fcntl(sockId,F_SETFL,O_NONBLOCK);
fcntl(client,F_SETFL,O_NONBLOCK);
while (1) {
if(client = accept(sockId,(struct sockaddr *)&clientAddress,&sin_size) == -1){
perror("accept");
}
cout <<"client "<<client<<endl;
fcntl(client,F_SETFL,O_NONBLOCK);
getMessage(client);
if(transmitFlag != -1)
sendRequest(client);
}
closeSocket();
}

Winsock c++ , program freezes on connection to an offline server

My program freezes when trying to connect to an offline server , it doesn't do that if it's online, i know it's trying to connect several times.
is there a way to do that without blocking the main code?
my connection function
bool WSockClient::ConnectServer(int PortNumber, char *IP)
{
SetClientSockAddr(&sockAddr, PortNumber, IP); // Settings
if((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
return false;
if(connect(hSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr)) != 0) // Connect to the server
return false;
//cout << "Attempting to connect to " << inet_ntoa(sockAddr.sin_addr) << endl;
return true;
}
By default, a socket will be 'blocking', meaning that certain calls (like connect) will block the execution of your program until the operation has been completed. On MS-Windows, you can change the socket to 'non-blocking' using a call to ioctlsocket.
For a non-blocking socket, the connect call will return immediately and you'll have to use select to find out if the connection was successful. You can find some additional info here

bind returns address in use even if no connection is established

I have a c++ code in which I am trying to establish a connection on a socket. But I firstly need to check if a connection already exist on a given port, and if it exists I need to close the connection. I have the code below and my problem is that when checking if the port is already connected it returs that it is even if connect has failed previously.
connected = false;
int sockfd;
void conn(int port) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
.....
int sockfd_t;
if ( (sockfd_t = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
cout << "Error opening socket_test " << endl;
return;
}
// check if address already in use
if (bind(sockfd_t, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
if(errno == EADDRINUSE) {
cout << "address in use: bind fail, port=" << port << endl;
}
// do something - close the connection if already connected
}
else {
cout << "bind ok, port=" << port << endl;
}
close(sockfd_t);
if ( (sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
cout << "Error opening socket " << endl;
return;
}
if (connect(sockfd, (struct sockaddr *) &adresse, sizeof(adresse))) {
cout << "Error connecting" << endl;
close(sockfd);
return;
}
connected = true;
}
int main() {
int port=3590;
while (!connected) {
conn(port);
}
cout << "CONNECTED";
// ..........
}
After running the program this is the output printed:
bind ok, port=3590;
Error connecting
bind ok, port=3590;
Error connecting
address in use: bind fail, port=3590 //???
CONNECTED!
I don't know why on the 5-th line of the print it displays "address in use:..." as the connect fails the first two times?
I think you have a misconception about what these socket operations do.
But I firstly need to check if a connection already exist on a given port, and if it exists I need to close the connection.
bind() gives a socket a local address, rather than having anything to do with checking if a remote address you are trying to connect to is accessible.
connect() connects the socket to a remote address.
When connecting a socket as a client (which is what I think you are trying to do), you don't need to check if there is already a connection, remote server can handle multiple incoming client connections to the same port. Binding is usually only important for servers.
if you don't bind before connecting, a socket will be assigned a random local port.
So, if you are a client, you do:
socket()
connect()
If you are a server, you do:
socket()
bind()
listen()
In your own question, the output makes sense when there is no server listening, but then a server comes online.
First two times, you bind a socket and it's successful, because nobody is using it to listen, then you fail to connect, because you just bound, and did not start a server (by calling listen()).
Then a real server on the same host binds that socket and starts listening, therefore you can't bind that port anymore (it fails), but you can connect, because the server is listening.

Winsock2's listen() function finds a connection for every port; even those that don't exist?

I'm attempting to create a method that listens for a connection request to a specific port using a TCP protocol, with no libraries other than those that come with the Windows OS. The method seems to work fine with creating a socket and binding to a port; the problem seems to be with the listen() function. Even with no connection request to any port, it continually returns the value of zero, meaning, straight off of Microsoft's website -
If no error occurs, listen returns zero.
The strange part is that this happens with all port values; it seems to find a connection request for randomly attempted ports, ranging from 1234, to 8000, to -154326. For each of these, it's returning a value of zero.
What it should be doing is continually running until a connection request is found (this is what SOMAXCONN apparently indicates); once again, straight off of Microsoft's website -
If there are no available socket descriptors, listen attempts to continue to function.
Here is the method itself -
bool listenOnPort(SOCKET networkSocket, int portNumber) {
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
if(error) {
cout << "Failed to start up Windows Sockets API." << endl;
return false;
}
if(wsadata.wVersion != 0x0202) {
WSACleanup();
cout << "Failed to find a valid Windows Sockets API." << endl;
return false;
}
SOCKADDR_IN address;
address.sin_family = AF_INET;
address.sin_port = htons(portNumber);
address.sin_addr.s_addr = htonl(INADDR_ANY);
networkSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(networkSocket == INVALID_SOCKET) {
cout << "Failed to create a network socket." << endl;
return false;
}
if(bind(networkSocket, (LPSOCKADDR)&address, sizeof(address)) == SOCKET_ERROR) {
cout << "Failed to bind to the port." << endl;
return false;
}
cout << "Listening for a connection to port " << portNumber <<"..." << endl;
listen(networkSocket, SOMAXCONN);
cout << "Found a connection!" << endl;
}
Any explanation/word of advice is appreciated - thank you ahead of time!
You've confused listen with accept. listen reserves the port for your application, and queues incoming connections. accept waits for an incoming connection (if one isn't already queued).
listen will succeed when there is no incoming connection attempt.
http://linux.die.net/man/2/listen
listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).
You must call "listen()" before you can call "accept()"; but "accept()" is the call that accepts new connections (and gives you a new socket for each new connection).
Here's the man page for "accept()":
http://linux.die.net/man/2/accept
Better, look at Beej's Guide for an excellent introduction to sockets programming:
http://beej.us/guide/bgnet/output/html/multipage/
PS:
And don't forget to call WSAStartup() if you're using Windows sockets :)

Socket Timeout in C++ Linux

Ok first of all I like to mention what im doing is completely ethical and yes I am port scanning.
The program runs fine when the port is open but when I get to a closed socket the program halts for a very long time because there is no time-out clause. Below is the following code
int main(){
int err, net;
struct hostent *host;
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(xxxx);
sa.sin_addr.s_addr = inet_addr("xxx.xxx.xxx.xxx");
net = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
err = connect(net, (struct sockaddr *)&sa, sizeof(sa));
if(err >= 0){ cout << "Port is Open"; }
else { cout << "Port is Closed"; }
}
I found this on stack overflow but it just doesn't make sense to me using a select() command.
Question is can we make the connect() function timeout so we dont wait a year for it to come back with an error?
The easiest is to setup an alarm and have connect be interrupted with a signal (see UNP 14.2):
signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */
alarm( secs ); /* secs is your timeout in seconds */
if ( connect( fs, addr, addrlen ) < 0 )
{
if ( errno == EINTR ) /* timeout */
...
}
alarm( 0 ); /* cancel alarm */
Though using select is not much harder :)
You might want to learn about raw sockets too.
If you're dead-set on using blocking IO to get this done, you should investigate the setsockopt() call, specifically the SO_SNDTIMEO flag (or other flags, depending on your OS).
Be forewarned these flags are not reliable/portable and may be implemented differently on different platforms or different versions of a given platform.
The traditional/best way to do this is via the nonblocking approach which uses select(). In the event you're new to sockets, one of the very best books is TCP/IP Illustrated, Volume 1: The Protocols. It's at Amazon at: http://www.amazon.com/TCP-Illustrated-Protocols-Addison-Wesley-Professional/dp/0201633469
RudeSocket Solved the Problem
I found a lib file that is tested in linux Fedora (Not Sure about Windows) that gives me the option of timeout. Below you can find a very simple Example.
#include <rude/socket.h>
#include <iostream>
using namespace std;
using namespace rude;
Socket soc;
soc.setTimeout(30, 5);
//Try connecting
if (soc.connect("xxx.xxx.xxx.xxx", 80)){
cout << "Connected to xxx.xxx.xxx.xxx on Port " << 80 << "\n";
}
//connections Failed
else{
cout << "Timeout to xxx.xxx.xxx.xxx on Port " << 80 << "\n";
}
soc.close();
Here is a link to the DevSite