C++ UDP Broadcast using ::write - c++

I am writing a UDP client/server application. The server is a broadcast server, that broadcasts on a particular port to two clients on the same subnet. Each client receives a datagram and sends a response to the server. Each client knows the ip address of the server in advance.
My client is basically as in the client example of http://man7.org/linux/man-pages/man3/getaddrinfo.3.html, i.e. it uses the connect() function to specify the endpoint of all outgoing packets. By using connected UDP, the client can use read() and write() to the socket file descriptor rather than sendto/recvfrom.
For my server, I want to adopt a similar approach - configure the socket for broadcasting, and call read/write on the file descriptor. I can bind() the socket to listen for incoming datagrams on the specified port, and these are collected fine.
Minus error checking, my server code looks like this:
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof int);
struct sockaddr_in servaddr;
memset((char*) &servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int success = bind(sockfd, (struct sockaddr*) &servaddr, sizeof servaddr);
int BUFSIZE = 256;
char buf[BUFSIZE];
while (1)
{
// this works fine
int bytes_read = read(sockfd, buf, BUFSIZE);
// WANT TO BROADCAST HERE
int bytes_written = write(sockfd, buf, bytes_read);
}
However, when I try and broadcast a packet in the write() line, I get a 'Destination address not specified' error. I could call connect() to set the destination address, but I don't think connect() works on a broadcast socket.
Is there a way of broadcasting using write() rather than sendto?

The problem with using connect() for broadcast is that (in addition to modifying the behavior of send()/write()), connect() will install a filter on the socket so that it only receives packets whose source-IP field matches the IP address specified in the argument to connect().
That means if you call connect() on your socket with a broadcast-address as its argument, then your socket will only receive packets coming from that broadcast-address -- but packets are never (AFAIK) tagged as coming from a broadcast address -- rather, their Source-IP field is set to the IP address of the computer that sent the packet, as usual. The upshot is that if you connect() your socket to a broadcast address, you won't receive any packets on that socket.

Related

winsock2 client return self port number

I'm using lib winsock2 in Visual Studio community, using simple client example.
After executing connect() function, would like to know how can I get/return self/source port number of open connection.
In winsock2, when a connection is established you can bind socket port to some specific port you want to use. For example, let´s say you are creating an UDP or TCP socket and you want that a specific local port is used. In that case you can do that by calling bind function ( https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind )
if (port != 0) {
int rv = -1;
struct sockaddr_in recv_addr;
ZeroMemory(&recv_addr, sizeof(struct sockaddr_in));
recv_addr.sin_family = AF_INET;
recv_addr.sin_port = htons(port);
recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
rv = bind(udp_channel->socket, (SOCKADDR *)& recv_addr, sizeof(recv_addr));
}
This is the same bind function you will use to set listening port when your socket will act as a server in UDP or TCP, it's the same.
In case you don't do socket binding, socket port will be assigned on connection. There seems to be the function getsockname that user207421 mentioned.
getsockname() or getpeername()
returning Structured data with short sin_family and char sa_data[] with different amount of data depending on the protocols used
after connection to server use fuction getsockname() or getpeername() to get the structured data we need to extract the data to get the port
you use function ntohs() for extracting the port data with macro function SS_PORT to convert struct to sockaddr_in
example:
sockaddr struc_;
int struc_len = sizeof(struc_);
/* connect function*/
getsockname(ConnectSocket, (LPSOCKADDR)&struc_, &struc_len);
int port_int_ = ntohs(SS_PORT(&struc_));
or you can define a ready-made structure / create your own, with a pointer to port number data.

Receiving broadcast packet addressed to 255.255.255.255 in C++

I have a device that is discovered by sending a broadcast packet to 255.255.255.255 on port 4930 and the device responds by sending a packet back to 255.255.255.255 on port 4930.
I have a snippet of C++ code which can send a packet to 255.255.255.255 on port 4930 (both source and destination port), but it can't receive a packet back from the broadcast address 255.255.255.255.
I can see the device is working fine, wireshark can see the packets coming back and forth and the propriety software supplied with the device can discover the device just fine, the problem is with the C++ program so please keep on topic with your responses.
Now, as I have said I can send a packet just find, but firstly I can't bind to the IP address 255.255.255.255 to receive the packets. I can change the multicast address to 239.255.255.250 and the socket will bind but I need the address 255.255.255.255.
My snippet of code is below, I am using VC++2010
bool CPTUProgramDlg::FindPTU(u_short port, const char * Destaddress){
{
//Data to send
char packet_data[10] = {0x44,0x43,0x55,0x44,0x5f,0x50,0x49,0x4e,0x47,0x00};
int packet_size=10;
SOCKET sock;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
// set SO_BROADCAST on a socket to true (1): (so we can transmit to 255 addr)
//In order to use broadcast the options of socket must change
char broadcastON = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcastON, sizeof broadcastON);
if (sock < 0)
return false;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(Destaddress); // Specify dest IP
sendto(sock, packet_data, packet_size, 0, (struct sockaddr*)&addr, sizeof(addr));
if (bind(sock,(struct sockaddr*) &addr,sizeof(addr)) != -1){
char Buff[512];
recv(sock,Buff,512,0);
}
closesocket(sock);
}
return 1;
}
Wireshark screenshot to prove packets are being send:
From the wireshark output its seen that the special device is using broadcast to communicate and will use the same port number as source and destination.
Normal socket communication will require using matching port numbers but broadcast messages cannot be exchanged over the same socket, especially when the port numbers do not match as seen with wireshark.
Binding on 255.255.255.255 (INADDR_BROADCAST) should generally work but may be limited by your OS privileges and permissions.
You may try to solve the problem by using two sockets - one for receiving and one for sending. Of course the listening socket have to be setup first and bound to 0.0.0.0 (INADDR_ANY) and port 4930. In this case there is no easy way to filter by destination address (as I wrongly written in my comment) because most standard socket APIs do not provide a way to get the destination addess from the socket. On Linux there is an exception - IP_PKTINFO at SOL_IP...
By using recvfrom you will get the source unicast address of the responding device(s). You have to note that if you have more that one such device on your network you will get more than one response.

Where does winsock store ip address of a socket?

Suppose I have a simple winsock server that has a listening socket, and then when a connection is accepted, it stores the socket in an array of sockets (to allow multiple connections).
How can I get the IP address of a specific connection? Is it stored in the socket handle?
As long, as the socket stays connected, you can get both own socket address and peer one.
getsockname will give you local name (i.e. from your side of a pipe)
getpeername will give you peer name (i.e. distant side of a pipe)
This information is available only when the socket is opened/connected, so it is good to to store it somewhere if it can be used after peer disconnects.
Yes it is stored in the socketaddr_in struct, you can extract it using:
SOCKADDR_IN client_info = {0};
int addrsize = sizeof(client_info);
// get it during the accept call
SOCKET client_sock = accept(serv, (struct sockaddr*)&client_info, &addrsize);
// or get it from the socket itself at any time
getpeername(client_sock, &client_info, sizeof(client_info));
char *ip = inet_ntoa(client_info.sin_addr);
printf("%s", ip);

Receiving UDP broadcast

I have to receive an UDP broadcast (in Ubuntu if that makes any difference). Using Wireshark, I can see the packet being sent from the server machine, and I can see it being received by my client machine, but my program is completely oblivious. This is what I have:
sockaddr_in si_me, si_other;
int s;
assert((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))!=-1);
int port=6000;
int broadcast=1;
setsockopt(s, SOL_SOCKET, SO_BROADCAST,
&broadcast, sizeof broadcast);
memset(&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = INADDR_ANY;
assert(::bind(s, (sockaddr *)&si_me, sizeof(sockaddr))!=-1);
while(1)
{
char buf[10000];
unsigned slen=sizeof(sockaddr);
recvfrom(s, buf, sizeof(buf)-1, 0, (sockaddr *)&si_other, &slen);
printf("recv: %s\n", buf);
}
It is compiled in debug mode, the asserts aren't being erased during compilation, and my program just blocks on recvfrom.
Is there any other hoop I have to jump through to receive an untargeted UDP broadcast?
Edit: just a bit more info, I have the two computers connected on a dedicated switch, no outside interference. I also have a second network card on my client computer that connects to the company network, which also works.
I can ping both the outside (Internet working) and my server machine (plus I can see the actual packets in Wireshark), but you never know what might cause this problem.
As it turns out my code is perfectly fine, as I thought it would be. There was a problem with the network setup itself.
For posterity, I had set up two static IP'd computers on their own hub, instead of using the built in DHCP server on the server machine to allocate the IP address for the other computer. Pretty localized for my problem but you never know..
To send and receive broadcast
Be sure that netmask is correct. in windows mask for broadcast packets does not matters, but not in linux.
bind socket to INADDR_ANY
setsockopt to BROADCAST
call sendto with sendaddr.sin_addr.s_addr = inet_addr("your_interface_broadcast_address").
or - call sento several times for each interface with its broadcast ip address.
call recvfrom. any time before calling recvfrom, set up length parameter.

poll() with non blocking udp socket

I am trying to make a c++ program work which is written by somebody else. I am having hard time understanding it. I am not even %100 sure that we can use poll() with a UDP socket but the code I am refactoring, is using poll() to read from udp socket as follows:
fd.fd = m_bsocket;
fd.events = POLLIN;
iPollResult = poll(&fd, 1, iTimeout);
if(iPollResult > 0)
{
int iReceivedByteCount = recv(m_bsocket, p_pBuffer, p_iBufferSize, 0);
if(iReceivedByteCount > 0)
{
*p_pReadSize = iReceivedByteCount;
}
else
{
eReturnValue = UDP_READ_ERROR;
}
}
return eReturnValue;
I tried sending udp packets to this program using command line:
echo "123" | nc -u 127.0.0.1 25
It looks like poll() always times out and returns 0, therefore I can not read anything.
I also wrote a small c# program that sends udp datagram, but I can not receive the message. I am wondering what I am doing wrong...
While UDP sockets can be used to connect to another host, they are mostly used "connectionless". Reading your question and comments it makes no sense that you have a connected socket. Instead it should be connectionless as suggested by WouterH in his comment.
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in sin = { 0 };
sin.sin_family = AF_INET;
sin.sin_port = htons(25);
sin.sin_addr.s_addr = INADDR_ANY;
bind(sockfd, (struct sockaddr *) &sin, sizeof(sin));
// Make socket non-blocking if needed
With the above code, whenever someone sends UDP packets to port 25 on any address of your host, your socket will intercept it. Use e.g. poll or select to know when data is available.
You don't need to call connect() as UDP is connectionless. You need to bind() the socket to the IP of the interface you are listening on or 0.0.0.0 (INADDR_ANY) for all interfaces. And when sending to a destination, use sendto().
For completeness: if you call connect() on a UDP socket, you are just setting a default destination for the send() function (then you can use send instead of sendto).
If you want to receive data, you always have to bind() the socket to the interface, or all interfaces. Beware that you will have to verify the source address from the messages you are receiving. So you might want to filter the sender by using recvfrom() and checking the source address.