I need to be able to send and receive UDP packets on the same port.
I am able to listen, on say port 5000, but my send uses a random high port.
The system I am working written in VB with does this and my need is to write a UDP responder for debugging various protocol issues.
I am using the Open Source C++ Sockets Library from http://www.alhem.net (Anders Hedstrom) and have been able to use the UdpSocket::Bind() to receive incoming UDP packets using the virtual function UdpSocket::OnRawData(), but have been unable to cause the UdpSocket::Open() (calls connect) to make the UdpSocket::Send() use the port chosen in Bind() (it uses random high number port instead).
Moving the Open() function doesn't help. I have posted a request on their forum - but believe from what I have read that it should be possible to do this, and I'm probably not understanding how to use UDP.
Does anyone have any ideas on what I should try?
--thanks--
System consists of a number of nodes
listening on same port (different ip
addr's). System [A] sends datagram to
System [B]. System [B] asynchronously
responds and send datagram(s) back to
[A] all using same port. Even if [B]
identifies [A]'s port, [A] is not
listening on that port
I'm not sure I understand the "all using the same port" phrase in that sentence. If A sends a datagram to B, B will know A's IP and port right away (a quick check of your library documentation reveals OnRawData has a struct sockaddr *sa parameter, if you cast it to sockaddr_in* you'll be able to extract the IP:port pair). You can use that IP:port to send datagrams to and A will receive them. A is not "listening" on that port in the sense that it haven't called listen() on the socket, but since A owns a socket that is bound to that port (whether explicitly by calling bind() or assigned random port by the OS) it will receive the data.
Now if you want ALL your communication between nodes to go through your fixed port, you can do that. You just have to send all your datagrams through your "listening" socket. If every node "listens" on the same port, it means every node owns a socket that is bound to that port. If you want datagrams sent from A to B to appear coming from this fixed port you have to send them through that socket. I'm guessing that's why bind() doesn't work for your sending socket - A has a socket bound to port X, then you create another socket and try to bind it to the same port X, bind() fails since the port is already taken (and you don't check for errors :), and then the OS assigns random free port above 1024.
Note 1: I use "listening" in quotes everywhere, because the concept is not very clear in the context of UDP sockets. Once you have created socket and bound it to a port, either by calling bind() explicitly or by sending data and letting the OS bind it to a port, you can receive data from everywhere through it. No listen() or accept() calls needed.
Note 2: You say that UdpSocket::Open() calls connect(), but that doesn't make much sense - connect() does very little for UDP sockets - it merely establishes a default address so you can use send() instead of sendto() and not specify address on every send.
Hope that clears things up.
Edit to address OP's comment: I've never used this library but according their UdpSocket documentation there are 4 overloads of the Bind() method and every single one of them accepts port in some way. None of them works for you?
A bidirectional communication link always involves two participants: a server-side and a client-side.
The client expects to communicate to a server on a defined port: that's why on the server-side one must bind() to a socket.
On the client-side, one must open a socket to the server: it doesn't really matter which socket is chosen (except for the need for it to be free).
In other words, don't try to specify a socket on the client-side: the network protocol stack will assign it to your client.
Related
I would like to send a UDP datagram from a specified port number WITHOUT binding (ex. when the port is already bound to another socket that I have no control over).
While I do appreciate the OS trying to keep everything nice and clean, and I cherish the bind() functionality, the question is as it is.
How to accomplish this with WSASendTo() or WSASendMsg()?
WSASendTo() will use whichever source IP/Port the socket is currently bound to. If the socket is not bound, WSASendTo() will perform an implicit binding first.
WSASendMsg() can use the IN_PKTINFO/IN6_PKTINFO structs to specify a source IP and source interface, but AFAIK the only way to specify a source port is through bind().
[Similar Questions]:
Problems using UDP sockets bound to the same port on Windows
Handling multiple UDP sockets listening on the same endpoint
None of which ever got resolved.
[Situation]:
On Microsoft Windows, I bind two UDP server sockets in the same process. This particular (not to say peculiar) operating system supports only SO_REUSEADDR, it does not support SO_REUSEPORT; and on top of that, SO_REUSEADDR acts like SO_REUSEPORT.
So, considering the above, I am left with binding socket A to 0.0.0.0:1234 and socket B to say 192.168.1.1:1234; if I'm to reuse the same port on the same machine.
Namely, I cannot bind both to the same IP address, since Microsoft Windows would not agree with that; since yet again, it does not support two sockets to be bound to exactly the same tuple of {SRC_ADDR,DST_ADDR, SRC_PORT,DST_PORT,PROTOCOL} even when SO_REUSEADDR is used on BOTH sockets.
So, I'm forced to bind to two distinct addresses, if I'm to use the same port on the same machine. Even though 0.0.0.0 represents any address, but in any case Microsoft Windows agrees, and binds the two sockets in such a configuration, without any error.
The binding operations, in such a configuration for the two UDP sockets, do succeed.
Problem:
Now, I'm having trouble getting these sockets to receive data as expected. Namely, I expect the two sockets to receive data. In reality, only the socket which got bound first receives data.
Any ideas?
Is it that the data is always received by the socket best matching the destination? If you wonder why I'm playing that way, it's because I'm trying to multiplex two libraries with two protocols over the same port, with the least amount of modifications.
If you want two ports are received same udp packet you should set option/flag broadcast for transmit socket.
Something like:
socket_.set_option(boost::asio::socket_base::broadcast(true));
In some cases (for some OS's) you should transmit packet to broadcast address instead of exact ip-address.
I'm trying to create a simple UDP broadcast class in c++ using the Boost Asio library.
Specifically, in the main class I'd like to instantiate a socket to both send and receive data. But I've seen three different ways of doing so, and I wanted to ask if anyone knew the difference? These are the methods I've seen:
The first after creating the socket using a io_context, opens it:
socket.open(udp::v4());
I've read somewhere that it works also in receiving after sending a packet, because calling socket.send(...) automatically binds the socket to a local endpoint (i.e. host address and a random port); but at this point anyone wanting to send a packet to this specific socket, how would be able to do so if the local endpoint is kind of "generated random" (the port is not known..).
The second method I've seen is first opening the socket then binding it to a local endpoint:
socket.open(udp::v4());
socket.bind(local_endpoint);
Finally the third method, consists of creating the socket with already a local endpoint, and use it without calling open():
udp::socket socket(io_context, local_endpoint);
So what would be the difference between the three, and would they all work? What would be the best way?
Thank you in advance!
The first method will create a socket without binding to a specific port. This is fine if you don't care about someone initiating the messages with you. IE: You send a message to a recipent, they can reply back because they received the sender's IP and Port along with the message.
If you want someone to be able to message you on a specific IP and port, you can initialize your socket like so:
socket_(io_service, udp::endpoint(udp::v4(), port))
I've created a packet socket
m_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
and attached a TX ring buffer. I fill out ethernet, ip and udp headers correctly and things work out great until the source and destination MACs happen to be equal. Then netcat (or any other utility/udp receivers) fails to receive the packet I sent. The packet is being sent according to tcpdump though.
I read somewhere that any network device would simply just ignore packets like this, but I still see this behavior on the loopback interface (why doesn't it loop back in this case?).
I only control the sender and due to performance reasons this is the way to go. However, one of the recipients may be located on the same computer and in this case either lo or eth0 will be used (depends on configuration).
How can I force the interface to not ignore these packets?
EDIT:
Using a raw packet socket socket for receiving shows that I do get both outgoing (PACKET_OUTGOING) and incomming (PACKET_HOST). However, using a more 'regular' UDP socket for receiving does not catch anything at all.
This seems to be to some odd behavior with raw sockets. See this related ticket on stackoverflow.
I have a UDP file descriptor in a C++ program running under Linux. I call connect() on it to connect it to a remote address and then read and write from that socket.
According to UNIX Network Programming, "Asynchronous errors are returned to the process for connected UDP sockets." I'm guessing that these asynchronous errors will cause the UDP socket to be closed by the OS, but the book isn't that clear. It also isn't clear what types of asynchronous errors are possible, though it's suggested that if the port on the remote machine is not open, the socket will be closed.
So my question is: Under what conditions will Linux close the UDP file descriptor?
Bad port number?
Bad IP address?
Any others?
connect() on an UDP socket just records the port number and IP address you pass in, so it'll only accept packets from that IP/port, and you can use the socket fd to send/write data without specifying the remote address for each send/write call.
Regarding this, async errors means if you send() something, and that send call results in an error occuring later (e.g. when the TCP/IP stack actually sends the packet, or an ICMP packet is later returned), a subsequent send will return that error. Such async errors are only returned on a "connected" UDP socket. (The linux udp(7) manpage suggest errors are returned whether the socket is connected or not, but testing shows this is not the cases at least when a sent UDP packet generates an ICMP error. It might be that send() errors are returned if you recv() on that socket, instead of subsequent send() calls produce an error )
The socket is not closed though, you'll have to close it yourself either by calling close() or exiting the program. e.g. if you connect() your UDP socket, and send to a port noone is listening to, an ICMP packet is normally returned and a subsequent send() call will fail with errno set to ECONNREFUSED. You can continue sending on that socket though, it doesn't get closed by the OS, and if someone starts listening on the port in the mean time the packets will get through.
UDP sockets are connectionless, so there is no real sense of "openness" state attached to them - this is unlike TCP sockets where a socket may be in any number of connection states as determined by the exchange of packets up to a given point.
The only sense in which UDP sockets can be opened and closed is in the sense that they are system level objects with some internal state and a file descriptor. Sockets are never automatically closed in the event of an error and will remain open indefinitely, unless their owning process terminates or calls close on them.
To address your other concern, if the destination port on the destination host is not opened, the sender of a UDP packet will never know.** UDP provides no means of receiver acknowledgement. The packet is routed and, if it arrives at the host, checked for correctness and either successfully received or discarded. There are a number of reasons why send might return an error code when writing to a UDP socket, but none of them have to do with the state of the receiving host.** I recommend consulting the sendto manpage for possible failure modes.
On the other hand, in the case of a TCP socket attempting to connect to an unopened port, the sender will never receive an acknowledgement of its initial connection request, and ultimately connect will fail. At this point it would be up to the sender to stop sending data over the socket (as this will only generate more errors), but even in this case however, the socket file descriptor is never automatically closed.
** See response by #Zuljin in the comments.
The OS won't close your socket just because an error has happened. If the other end disappears, you can continue to send messages to it (but may receive further errors).