Port to Port data transfer with UDP - c++

I'm working on this project where the source and destination ports are specified for sending a message via a UDP socket in C++. I've got the TCP portion of the project working fine, but I don't understand how to specify both the source and destination ports when setting this up.
The way I would know how to do it is the "receiver" sets up a recvfrom() call, with the port that the "sender" will also use in the sendto() command... but it would need to be the same port.
So, given that I need port x on the "receiver" to talk to port y on the "sender", how would I do that?
Thanks

You can define a source port when you call bind on the sender side. For instance:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) { /*error*/}
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(source_port); // here
int res = bind(sockfd,(struct sockaddr*)&sin, sizeof(sin));
if (res < 0) { /*error*/}
And the destination port goes into the sockaddr parameter passed to sendto.

If this is one-to-one mapping, i.e. one source talks to one destination, then simply bind(2) the local port and connect(2) to the remote IP and port (contrary to common misconception you can connect UDP sockets). Do that on both sides (with appropriate remote and local IPs/ports of course), and now you can just use recv(2) and send(2) without explicit addressing.
If one side needs to wait for the other to send the first packet, then extract source address/port received with recvfrom(2), and then connect(2) to it.
If, on the other hand, one side acts as a multi-client server, then do same bind(2)/connect(2) dance on the client, but only do bind(2) to local port and then use recvfrom(2)/sendto(2) on the server.

If you need simultaneous duplex communication, then you should use sockets in blocking mode -- fcntl(...O_NONBLOCK...), and use select() to determine if your socket is writable or readable or both. Here is a nice example on how this can be done http://www.lowtek.com/sockets/select.html

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.

udp socket sendto implicit bind

I'm looking at the udp client example here:
http://www.linuxhowtos.org/data/6/client_udp.c
snippet:
/* UDP client in the internet domain */
struct sockaddr_in server, from;
//...snipped
sock= socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("socket");
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if (hp==0) error("Unknown host");
bcopy((char *)hp->h_addr,
(char *)&server.sin_addr,
hp->h_length);
server.sin_port = htons(atoi(argv[2]));
length=sizeof(struct sockaddr_in);
//... snipped
n=sendto(sock,buffer,
strlen(buffer),0,(const struct sockaddr *)&server,length);
if (n < 0) error("Sendto");
n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
if (n < 0) error("recvfrom");
//... snipped
I'm trying to understand how it knows where to receive the message from. I know when sendto is called an available port is chosen and that is embedded in the udp message and the server application can read that and reply to it. How does the client code know to receive a message on that port?
This answer: https://stackoverflow.com/a/48245273/2748602 indicates there is kind of an implicit bind when the sendto function is called. How does it work? Is it in fact a bind with a random available port number that is as permanent as if I had called bind or something else? It seems there's some aspect of permanence. Just interested in a little more detail.
There is an implicit bind if the socket is unbound since all packets have to carry both a source port. So the API assumes that if you didn't care enough about the port to bind your socket beforehand, then it can just bind the socket to a random port. And while unfortunately I don't know the implementation details of sendto, I can offer some official documentation.
For Linux, from the udp man page:
When a UDP socket is created, its local and remote addresses are
unspecified. Datagrams can be sent immediately using sendto(2) or
sendmsg(2) with a valid destination address as an argument. When
connect(2) is called on the socket, the default destination
address is set and datagrams can now be sent using send(2) or write(2)
without specifying a destination address. It is still possible to
send to other destinations by passing an address to sendto(2) or
sendmsg(2). In order to receive packets, the socket can be bound to a
local address first by using bind(2). *Otherwise, the socket layer
will automatically assign a free local port out of the range defined
by /proc/sys/net/ipv4/ip_local_port_range and bind the socket to
INADDR_ANY.
For Windows, a snippet from the documentation for Winsock 2's sendto:
If the socket is unbound, unique values are assigned to the local
association by the system, and the socket is then marked as bound. If
the socket is connected, the getsockname function can be used to
determine the local IP address and port associated with the socket.
... there is kind of an implicit bind when the sendto function is called. How does it work? Is it in fact a bind with a random available port number that is as permanent as if I had called bind or something else?
man ip(7):
ip_local_port_range (since Linux 2.2)
This file contains two integers that define the default local
port range allocated to sockets that are not explicitly bound
to a port number—that is, the range used for ephemeral ports.
An ephemeral port is allocated to a socket in the following
circumstances:
* the port number in a socket address is specified as 0 when calling bind(2);
* listen(2) is called on a stream socket that was not previously bound;
* connect(2) was called on a socket that was not previously bound;
* sendto(2) is called on a datagram socket that was not previously bound.

POSIX UDP socket not binding to correct IP

I'm in the process of writing a project for college involving writing a chat client and server using POSIX sockets and C++.
The clients are supposed to converse with each other using P2P, such as each client has his own open UDP socket through which he sends and recieves messages from/to other clients.
My problem is 2-fold:
My UDPSocket class constructor seems to be ignoring the port number completely, binding to port 65535 regardless of the parameter.
The port is binding to IP 255.255.255.255 rather than my own IP (10.0.0.3), or at least that's what i get when I call getpeername.
To the best of my knowledge passing INADDR_ANY should bind to my local address, and passing port number 0 should make the OS choose a free port, what am I doing wrong?
This is the constructor of my UDPSocket class:
UDPSocket::UDPSocket(int port){
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
// clear the s_in struct
bzero((char *) &in, sizeof(in)); /* They say you must do this */
//sets the sin address
in.sin_family = (short)AF_INET;
in.sin_addr.s_addr = htonl(INADDR_ANY); /* WILDCARD */
in.sin_port = htons((u_short)port);
fsize = sizeof(from);
//bind the socket on the specified address
if(bind(socket_fd, (struct sockaddr *)&in, sizeof(in))<0){
perror ("Error naming channel");
}
}
This is the initialization:
m_Socket = new UDPSocket(0);
And this is the method I use to retrieve the binded address: (UDPSocket inherits Socket)
std::string Socket::GetSocketAddress()
{
struct sockaddr_in addr;
int len = sizeof(addr);
getpeername(socket_fd, (struct sockaddr*)&addr, (socklen_t*)&len);
char ipAddressBuffer[50];
memset(ipAddressBuffer, 0, sizeof(ipAddressBuffer));
sprintf(ipAddressBuffer, "%s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
return ipAddressBuffer;
}
Any help would be greatly appreciated,
Avi.
You're using getpeername , which gives you the remote address of a connected socket. If you check the return value of getpeername(), it should indicate failure.
You need to use getsockname() instead of getpeername() to get the address of your local socket
You need to check that getsockname() succeeds.
Note that your socket is bound to the special 0.0.0.0 address, which means "all local interfaces", so that's what getsockname() will also return.
Answering the more general question "How to set up peer-to-peer communications with UDP":
With UDP sockets, while you can use connect, you generally don't want to, as that restricts you to a single peer per socket. Instead, you want to use a single unconnected UDP socket in each peer with the sendto and recvfrom system calls to send and receive packets with a different address for each packet.
The sendto function takes a packet and a peer address to send it to, while the recvfrom function returns a packet and the peer address it came from. With a single socket, there's no need to multiplexing with select or poll -- you just call recvfrom to get the next packet from any source. When you get a packet, you also get the peer address to send packets (back) to.
On startup, your peer will create a single socket and bind it to INADDR_ANY (allowing it to receive packets on any interface or broadcast address on the machine) and either the specific port assigned to you program or port 0 (allowing the OS to pick any unused port). In the latter case, you'll need to use getsockname to get the port and report it to the user. Once the socket is set up, the peer program can sendto any peer it knows about, or recvfrom any peer at all (including those it does not yet know about).
So the only tricky part is bootstrapping -- getting the first packet(s) flowing so that peers can recieve them and figure out their peer addresses to talk to. One method is specifying peer addresses on the command line when you start each peer. You'll start the first one with no arguments (as it has no peers -- yet). It will just recvfrom (after socket setup) to get packets from peers. Start the second with the address of the first as an argument. It sends a packet (or several) to the first peer, which will then know about the new peer as soon as it gets the first packet. Now start a third client with the addresses of the first two on the command line...

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.

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.