sendto and recvfrom in the same program? - c++

this is my first time asking a question, and the first time I couldn't find an answer by just searching this site. so please go easy on me if I am doing it wrong.
Using Winsock. I need to send AND receive a packet of information to another computer running the same program. the type of connection should be UDP(non blocking I guess?)and using a data-coupled model.
do I need to be sending and receiving the information using different threads?
I know the data sends just fine but it is not being received at all.
I can easily have on program send and a completely different program recv but it seems the principles don't carry over to what I am trying to do.
should I use the same sockaddr_in struct for the recvfrom and sendto? or can they use the same one? how about slen? doesn't matter I have tried both and neither work.I have tried using one port to send and one to recieve, I have tried having one port to do both. nothing. I am relatively new to Winsock so sorry if I sound hopeless or missing something horribly obvious. At this point I just really need some help or at least a point in the right direction I don't care how many ports I just want to see the recv printf incoming with the right data.
winsock errors are
bind failed 10048 and recv failed 10022
I will also mention I looked into a concept called setsockopt suggested by MSDN but it just ended up furthering my confusion. am I missing something?
here are some relevant functions.
void UDPNetwork::initserver()
{
initRemote();
slen2= sizeof(si_other);
if ((_recvSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
printf("failed to create socket: %d", WSAGetLastError());
}
_recvSocket = (AF_INET, SOCK_DGRAM, 0);
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
if (bind(_recvSocket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d",
WSAGetLastError());
/* system("PAUSE");
exit(EXIT_FAILURE);*/
}
}
void UDPNetwork::initclient(){
slen = sizeof(si_other);
_sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (_sendSocket == SOCKET_ERROR)
{
printf("failed to create socket... ");
exit(EXIT_FAILURE);
}
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
}
void UDPNetwork::send(float x, float y, float z)
{
sprintf(bufOut,"%f,%f,%f", x, y, z);
if (sendto(_sendSocket, bufOut, strlen(bufOut), 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR)
{
printf("sento() failed with error code : d%", WSAGetLastError());
exit(EXIT_FAILURE);
}
//printf("Sent: %s\n", bufOut);
}
void UDPNetwork::recv(char *msg)
{
float ax = 0; float ay = 0; float az = 0;
memset(msg, '\0', BUFLEN);
recv_len = recvfrom(_recvSocket, msg, BUFLEN, 0, (struct sockaddr*) &si_other, &slen);
int nError = WSAGetLastError();
if (nError != WSAEWOULDBLOCK&&nError != 0);
{
printf("Recv failed with error code : %d",
WSAGetLastError());
//system("PAUSE");
//exit(EXIT_FAILURE);
}
recv = buf;
sscanf_s(msg, "'%f,%f,%f", &ax,&ay,&az);
printf("RECV: %f %f %f\n", ax, ay, az);
}

Most UDP receivers will send data back to the same IP:Port that the reeived data was sent from. So by creating two different sockets, you are using two different IP:Port pairs, which is likely why you are not receiving data. The data is likely being sent to a different IP:Port than the one you are reading on.
For UDP, you usually do not need to create separate send and receive sockets. You can create one UDP socket and use it for both sending and receiving, so the sending IP:Port matches the receiving IP:Port. The only time you should need to create separate sockets is if the receiver intentionally sends its data to a different IP:Port than what the sending socket is using.

after searching deep into the MSDN archives I found this helpful little page
https://msdn.microsoft.com/en-us/library/bb530747%28v=vs.85%29.aspx
hopefully this will add some insight to my problem. I will update on weather this resource ended up solving my problems

Related

Trying to receive incoming UDP packets, empty buffer

I'm trying to read these incoming UDP packets using Wireshark:
I'm using the next code:
struct sockaddr_in si_other;
struct sockaddr_in remaddr; /* remote address */
int slen = sizeof(remaddr);
int s, recvlen;
char buf[BUFLEN];
char message[BUFLEN];
WSADATA wsa;
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//create socket
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR) //IPPROTO_UDP
{
printf("socket() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
//setup address structure
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
if (bind(s, (struct sockaddr *)&si_other, sizeof(si_other)) < 0) {
perror("bind failed");
return 0;
}
u_long nMode = 1; // 1: NON-BLOCKING
if (ioctlsocket(s, FIONBIO, &nMode) == SOCKET_ERROR)
{
closesocket(s);
WSACleanup();
return 0;
}
//start communication
while (1)
{
printf("waiting on port %d\n", PORT);
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Done");
puts(buf);
}
The address I'm binding is 192.168.1.1 and the port 1234.
And the given output by WSAGetLastError is an empty buffer error: 10035
I tried to disconnect firewall, antivirus...and I'm running the program as a administrator, and it didn't help.
Why is the buffer empty? I'm clearly seeing that there are packets coming, what could be blocking the incoming data to the socket?
the given output by WSAGetLastError() is an empty buffer error: 10035
No it isn't. 10035 is WSAEWOULDBLOCK. That means the operation would block in blocking mode, i.e. that no data was present to be received at the moment you called recvfrom().
The address I'm binding is 192.168.1.1
The IP 192.168.1.1 is shown as a gateway
These two statements are mutually inconsistent. If it's a gateway it's an external IP address, and if it's an external IP address you can't bind to it.
I tried INADDR_ANY and it didn't help
Not surprising. If you're not 192.168.1.1 you can't receive its messages. Unclear why you would think otherwise.
As #EJP mentioned 10035 is WSAEWOULDBLOCK, i.e., no data is ready. The cause of this is that the receiver is 192.168.1.1 which is your gateway's IP address, thus not a local IP. In this case you cannot receive the packets in a normal manner.
You can receive these packets, even though they are not meant for you, by using an UDP sniffer, e.g., using libpcap.
Thanks for the answers, they pointed me to the right direction. I 've got now the program working and I'm able to receive the incoming UDP packets.
The solution was to "sniff" these UDP packets, winsock allows that using the WSAIoctl function after bind, in my case adding the next code to the above program (after the bind function):
if (WSAIoctl(s, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD)&si_other, 0, 0) == SOCKET_ERROR)
{
printf("WSAIoctl() failed.\n");
return 1;
}
I hope could help somebody else with similar issue.

How to run a live server win winsock?

So I want to run a live server on my pc to connect and get info from someone else. I thought I can let the other person connect to my ip address on a port that is not used. So for example if my hypothetical ip address is 214.231.34.12 and port 50000 and I open te connection and give this information to someone, they can connect to it and send me information through TCP.
I thought I could use this code:
// TCPClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
/*
Live Server on port 50000
*/
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("214.231.34.12");
server.sin_family = AF_INET;
server.sin_port = htons(50000);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
puts("Connection accepted");
//Reply to the client
message = "Hello Client , I have received your connection. But I have to go now, bye\n";
send(new_socket, message, strlen(message), 0);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
But it is failing at binding the connection. This whole TCP and winsocket stuff is totally new to me and I do not understand how I should approach this differently. I know this code is not receiving any information yet, it is just the connection that I try to get working at the moment. Is this not the right way to set this up?
The bind() fails with windows socket error 10049
There are plenty of obstacles for establish a TCP connection over internet:
internet itself: bad/unstable connection, dynamic ips, etc
ISP: maybe your ISP blocks some ports or ips
router: router firewall, NAT traversal problems, upnp, etc
OS: windows firewall, antivirus, port blocked/in use
YOUR APP: maybe a code mistake
Is a complete new world link to pcs over internet, the concept is the same, but implement it......
So it might be an answer, but maybe I have to use another port as datenwolf suggested.
I found that it is not possible to bind to my ISP's ipaddress. So I have forward the port I want to use and then connect to the ipaddress of my computer, as mentioned here:
connecting to an IP address instead of localhost?
I tried that, so I changed the ipaddress in code to:
//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("192.168.178.93");
server.sin_family = AF_INET;
server.sin_port = htons(50000);
And then when I connect to 214.231.34.12 and port 50000 with telnet, the connection works! I just wonder if this is a valid result?

c++ WINSOCK recvfrom no get data from network

i have problem because my server dont get UDP data. Ports on router are forwarded, data income to local-server network (it is visible on sniffer (3) ) but server dont receive it.
Server and server network screen
You can see 1 and 2 TCP packets correct income to server on connected sockets. But my client then send UDP data to server and data enter to local-server network (see that sniffer detect it on 3) but server dont take it.
Here is code of client:
struct sockaddr_in si_other;
int s, slen = sizeof(si_other);
char buf[10];
char message[10];
WSADATA wsa;
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//create socket
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
printf("socket() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
//setup address structure
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(14996);
si_other.sin_addr.S_un.S_addr = inet_addr(server ip);
memcpy(message, "cokolwiek", 8);
//send the message
if (sendto(s, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
But its not problem with client. Here is server code but i think it is also correct:
SOCKET s;
struct sockaddr_in server, si_other;
int slen, recv_len;
char buf[10];
WSADATA wsa;
slen = sizeof(si_other);
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(14996);
//Bind
if (::bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//blocking on it, waiting for data
if ((recv_len = recvfrom(s, buf, 10, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
//print details of the client/peer and the data received
printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("Data: %s\n", buf);
Some description that may help - main server loop is select() and when client ask for order, server send order back to client and starts proceeding command.
server:
while (1) {
select()
if (socket is in FD_SET)
get data, send it back and handleCommand()
}
handleCommand() {
tcp data exchange
wait for udp packet - it fail
}
client:
sendCommand()
//another receiving commands thread
while (recv) {
handle command
tcp data exchange
send udp data
}
Pls dont give me answears to do it in another wait. I need to punch hole for NAT Traversal. What problem is that? Another listener grabbing my data? But netstat -nop UDP -a didn't give information that something other is listening, and bind socket didn't failed. Also another important information That code work on the begining of program, i mean server receive data but later not.
Okey, so as ElderBug said
Are you sure you setup the UDP server socket before you send the data ? It's not clear in your question
Yep, it was my fault. The miniseconds decided that sending data on one machine was executed before setting up listener on server. Thank you for answer.
But i dont exactly understand the problem. Shouldn't that data income to receive buffer and wait for "grabbing" it by recvfrom function?

Winsock UDP broadcast packets not sent

I'm encountering a strange issue using winsock when multiple network adapters are active but then one is disconnected.
This is the basic scenario:
Wifi and Ethernet are active and connected
Launch app, send UDP broadcast and receive response
Unplug Ethernet, restart app and try to send again - Nothing is sent (Wireshark shows nothing, seems Windows is dropping them before they get to NIC?)
Disable the disconnected Ethernet adapter and try again - sends fine over Wifi and gets response.
Now this is a very specific scenario but I believe it's happening in other cases, this is just the only way I know to reproduce it every time.
The following is a code snippet of the UDP send, for this example assume dstAddrStr is 192.168.1.255
struct sockaddr_in sa_remote;
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
printf("Error creating socket: %ld\n", WSAGetLastError());
}
int enable = 1;
if ((setsockopt(sock,
SOL_SOCKET, SO_BROADCAST, (char*)&enable, sizeof(enable))) == -1) {
printf("Error enabling broadcasts: %ld\n", WSAGetLastError());
}
const MIB_IPADDRROW & row = iptbl->table[i];
uint32 ipAddr = ntohl(row.dwAddr);
uint32 netmask = ntohl(row.dwMask);
uint32 baddr = ipAddr & netmask;
if (row.dwBCastAddr) baddr |= ~netmask;
char dstAddrStr[32]; Inet_NtoA(baddr, dstAddrStr);
memset(&sa_remote, 0, sizeof(struct sockaddr_in));
sa_remote.sin_family = AF_INET;
sa_remote.sin_addr.s_addr = inet_addr(dstAddrStr);
sa_remote.sin_port = htons(_DST_PORT);
if (sendto(sock, dpString, strlen(dpString), 0, (struct sockaddr *)&sa_remote, sizeof(struct sockaddr_in)) < 0){
printf("UDP send error Error: %ld", WSAGetLastError());
break;
}

Server socket finishes when client closes connection

I'm trying to create a server socket with C++ in order to accept one client connection at a time. The program successfully creates the server socket and waits for incoming connections but when a connection is closed by the client the program would loop endlessly. Otherwise if the connection is interrupted it would keep waiting for new connections as expected. Any idea why this is happening? Thanks
This is my C++ server code:
int listenfd, connfd, n;
struct sockaddr_in servaddr, cliaddr;
socklen_t clilen;
pid_t childpid;
char mesg[1000];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(32000);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 1024);
while (true) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
if ((childpid = fork()) == 0) {
close (listenfd);
while (true) {
n = recvfrom(connfd, mesg, 1000, 0, (struct sockaddr *)&cliaddr, &clilen);
sendto(connfd, mesg, n, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
mesg[n] = 0;
printf("%d: %s \n", n, mesg);
if (n <= 0) break;
}
close(connfd);
}
}
For some reason when the client closes the connection the program would keep printing -1: even with the if-break clause..
You never close connfd in parent process (when childpid != 0), and you do not properly terminate child process that will try to loop. Your if block should look like :
if ((childpid = fork()) == 0) {
...
close(connfd);
exit(0);
}
else {
close(connfd);
}
But as you say you want to accept one connection at a time, you can simply not fork.
And as seen in other answers :
do not use mesg[n] without testing n >= 0
recvfrom and sendto are overkill for TCP simply use recv and send (or even read and write)
mesg[n] = 0;
This breaks when n<0, ie. socket closed
The problem is your "n" and recvfrom. You are having a TCP client so the recvfrom won't return the correct value.
try to have a look on :
How to send and receive data socket TCP (C/C++)
Edit 1 :
Take note that you do the binding not connect() http://www.beej.us/guide/bgnet/output/html/multipage/recvman.html
means there is an error in recieving data, errno will be set accordingly, please try to check the error flag.
you've written a TCP server, but you use recvfrom and sendto which are specific for connection-less protocols (UDP).
try with recv and send. maybe that might help.