File Exchange

image thumbnail

A simple UDP communications application

version (2.89 KB) by Kevin Bartlett
Sends/receives UDP packets using Matlab's Java interface.


Updated 29 Mar 2010

View Version History

View License

UDP packets are used to send data from one computer to another over a network or from one application to another within a single computer.

The judp.m program uses Matlab's ability to call Java code to enable it to send and/or receive UDP packets. One Matlab session can communicate with another Matlab session (on the same machine or over the network) or it can communicate with a completely different program (again, on the same machine or over the network).

Cite As

Kevin Bartlett (2021). A simple UDP communications application (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (76)

Matt Fetterman

very good. I modified it so that it returns socket. That way it can be used in a persistent way. if there is UDP data sent while we are not listening, we can come back and get this data.

Johannes Ostler


Tamer Koban

Mobien Shoaib

Thank you very much for your contribution. The only comment I've is you have prevented UDP blocking mode by checking for timeout <= 0 on line 102 of your function. If you change it to timeout < 0, we can set timeout value to 0, which means UDP can wait for packet infinitely, a requirement of my application.

David Neal

Sara Ghayouraneh

Hello Kevin. I have an issue I wonder if you and your code can help me solve it. I am trying to get data coming into a device and import it into MATLAB. I am connected to the same network with my laptop and the device. This link shows that I get the UDP packets, but I don't know how to get the data into MATLAB. Do you know if your code can do anything with this issue? I am terribly stock at this point.

thank you very much,

ricardo rodriguez

Kevin Bartlett

@Mehmet--I don't know anything about the inner workings of Simulink, so I can't answer your question about using judp.m with it. I will add, though, that you may want to consider using jtcp.m (also on FileExchange), rather than judp.m for your application. The TCP protocol is generally slower than the UDP protocol, but it has error-checking built into it to correct for dropped packets, etc.

Mehmet Can Erdem


I tried this function and saw that data transmission speed is much better than MATLAB's built-in functions.
I wonder if we could use this function in Simulink environment.

If not, do you have any suggestions for achieving high bit rates rather than using built-in functions (blocks) in Simulink? I tried many approaches including Simulink Desktop Real-time Packet I/O blocks in external mode, but still I couldn't reach the desired bit-rates.

Again, thanks for sharing this file!

Kevin Bartlett

@Pranav--"help judp" will tell you that judp.m sends and receives its data in int8 format. You cannot send hex numbers directly.

Before sending, convert to decimal and thence into int8:
myHexNum = '84';
myInt8Num = typecast(hex2dec(myHexNum),'int8');
On receiving the data at the other end, convert back to decimal and thence to hex:
==> '84', which is what you started with.

Pranav Thiagarajan


Thanks for the function. I am using it receive data from a radar kit. In the process, it is converting some hex numbers that are received into positive decimal numbers and some others into negative.

For eg. 0x19 becomes 25
0x84 becomes -124

Do you know why this happens?

Thanks again.


@Kevin Bartlett. Ahh that's true. No it still must be UDP. I'll keep hunting. But thanks for all your help. Your code is easy to understand and working great!

Kevin Bartlett

@KdG. I'll admit up front that I am not a networking expert. But I can tell you that sending messages to a fixed IP does NOT make it TCP. The distinction between UDP and TCP is that TCP is a sort of two-way conversation: the sender expects to get back a confirmation that the packet has been received; if no confirmation comes back, the sender sends the same packet again (and again and again) until it gets confirmation. The UDP protocol does not involve sending and receiving confirmations--the UDP packets are just hurled into the ether and forgotten. This makes TCP the more reliable of the two protocols, but also involves a lot of overhead. So you can send a UDP packet to a fixed IP. You can also send it to more than one recipient, either by invoking "send" twice or using what's called a "broadcast" address (I think the broadcast approach may have some downsides in terms of slowing down the network for everyone else--it might not make you very popular). Best of luck.


@Kevin Bartlett. No worries! Thanks for your quick reply, makes sense. I wasn't quite sure how UDP worked. Both programs are running on the same computer, but the data sending program is simulating sending messages to something else (with a fixed ip, not sure if this makes it TCP?). I wanted to tap in and get them into matlab as well. Maybe that's not possible. I don't have the other program its pretending to send to so I'm not exactly sure how they communicate either. Steep learning curve :)

Kevin Bartlett

@KdG, you cannot direct judp.m to receive from a particular address--that's not the way UDP messaging works. What you CAN do is call judp.m with the [mssg,sourceHost] = judp('receive',... syntax. You could then tell your program to ignore the message if it came from the wrong source IP. I'm not sure I'm fully understanding your setup, but if both your programs are running on the same computer, there is no advantage to using the actual IP address of the computer, rather than the "loopback" address. Does this make sense?



I'm only just getting my head around the UDP thing, so apologies in advance for what may not be feasible. I can recieve UDP packets from another program if I use in the other program but not if I set a specific IP address. Is there a way I can direct judp.m to recieve from a specific ip address? Or should it be listening on everything anyway?

Debayan Ghosh


Kevin Bartlett

@nick--It might be easiest if you got judp working between two Matlab sessions before you go trying to receive packets from some other program. On linux and (I believe) on Macs, you can have two Matlab sessions running on the same local machine; on Windows I think you would have to have the two sessions on separate computers.

Follow the first example you see in 'help judp' pretty much exactly. In one session, type:

In the second session (before the 1-second default timeout expires), type:

Make sure that port 21566 is open in your firewall and substitute the receiving machine's IP address for "" (alternatively, if both Matlab sessions are on the same machine, you can use the "loopback" address:

If this doesn't work, you likely have something in your network blocking the UDP packets, which I'm not going to be able to help you with. You might try installing the wireshark packet-sniffing application and see if you see the UDP packets coming in on your network interface (or the loopback interface, if you're using that). Note, though, that on Windows (and Macs?) wireshark sees the packets BEFORE the built-in firewall does, so just because you see the packets arriving on wireshark, it doesn't mean they are getting to Matlab.

Sorry I can't be more help. Good luck.


hello :) im looking through the code and it looks sick, although im having some troubles.

i need to receive data in MATLAB from unity (VR program which will be sending data dynamically)

i first just want to receive the data but it isnt working ;(

i have tryed udp.Receive but no good.

the goal is to get unity to send a number between 0 and 1 (eg: 0.937262) and for matlab to recieve it.

both programs will be running off my computer.

could you please help, anything ideas or anything would be great thanks



Kevin Bartlett

@Habib--By "server", I presume you mean the application that will be SENDING udp packets, and by "client" you mean the application that will be RECEIVING udp packets?

If this is correct, then the Matlab side of the conversation is simply "judp('send',21566,'',int8('Howdy!'))"...again, you'd have to substitute the correct port number for 21566, and the correct IP address for ''.

As for the client (non-Matlab) side of the conversation, I'm not going to be able to help you--that's going to be entirely dependent on the application you are using. You may need to be sure that the specified UDP port is open in your firewall (although this shouldn't be necessary if both your client and server applications are running on the same computer.

Habib Khan

Thanks for the Reply. I have Matlab on the server but for client I am using another application which is not based upon Matlab. How can I use judp for such case?

Kevin Bartlett

@Habib--If you type "help judp", you should see three examples you can run. In the first of these, you type "mssg = judp('receive',21566,10); char(mssg')" in one Matlab session, and "judp('send',21566,'',int8('Howdy!'))" on the other (this assumes you are using port 21566 and that the IP of the receiving computer is, so you will have to modify these commands for your particular system). The receiving Matlab session should now have a variable called 'mssg' on its workspace containing the word 'Howdy'.

Habib Khan

I have downloaded the file but when I run the file in Matlab, the following error occurs.

Error using judp (line 50)
Not enough input arguments.

which is obvious since the function judp demands certain arguments.
How can I tackle the problem

Russ Howell

Greetings, All. I answered my own question from below. It appears that, overnight, my beloved Windows firewall had empowered itself to block UDP communications to Matlab. After correcting that in Windows, the "Simple UDP Communications App" works a treat (as they say in England). I give it five stars: got a good beat, and easy to dance to!

Russ Howell

I downloaded the judp.m file, and for several days it worked flawlessly. Suddenly yesterday I began to receive: "error using judp (line 166)"
"judp.m--failed to receive UDP packet; connection timed out".

I can't see that I've changed anything. The judp function is in a script that hasn't changed from when it worked well. Any ideas?

Kevin Bartlett

@Luca Gacy--sending the value of 59 to a computer with IP address via the (open) UDP port 21566 would be achieved with the line:


The question is whether Motion Composer is going to understand 59 expressed as an int8 value as an ASCII character. If not, you might be better off using jtcp.m, which is more complicated to use, but is not limited to transmitting int8s.

Email me at if you have further questions.

Luca Gacy

Hi, I am trying to setup a connection between Matlab and a program called Aerotech Motion Composer in order to control a translation table through matlab rather than its native environment. I have the connection setup on Motion Composer's side to receive an ASCII value of 59 (;). I can't figure out how to send this ASCII value to this other program. I am a little new to Matlab so I can give you extra information if it is necessary. Thanks in advanced for your reply.

Pedro Gonçalves

Works very good and faster then the one implemented by Matlab


Vinicius Goecks

Kevin Bartlett

@Bryan Womack--I'm away from work at the moment, and with no access to Matlab, I'm unable to troubleshoot this.

I can tell you, though, that the "Who has..." message is not generated by my code. The "SEND" portion of my code consists of calls to Java programs that are pretty much black boxes to me. Perhaps one of them is generating this message? You might try putting in some diagnostic "disp" or "keyboard" calls into my code to see how far it gets and at what stage the "Who has" message is generated. For example, just after where my code says "if action == SEND" and just before "addr = InetAddress.getByName(host);" insert the string "keyboard" and run the program again. This way, you can execute the lines of SEND code one by one and hopefully find the problem.

Bryan Womack

Sup Fam,

I am trying to use this example code to send a UDP packet to a microcontroller running lwIP. I am able to read broadcasted data using the 'receive' command but when I attempt to use 'send', it doesn't do much.

When I monitor the Ethernet port over wireshark I see my computer sending out an ARP that says "Who has Tell"

In this ARP the IP ending in .93 is the microcontroller and the IP ending in .77 is the computer.

Is it not possible to just blindly send packets? The call I am making looks like this:

judp('send',5555,'',int8('GOOD GOLLY'))

To be clear on the behavior I am seeing:

1) Call judp as described above
2) Check wireshark
3) "Who has Tell"


Kevin Bartlett

@Joost--I'm afraid that is just the nature of UDP communications. The UDP protocol discards packets if they are coming in too quickly for the network or computer to handle. This makes UDP communications very resilient, but at the cost of being "lossy". If you really need every packet, you can switch to using the TCP/IP protocol instead (see my jtcp.m program, also in the File Exchange). The danger here is that the TCP protocol does NOT discard packets if they are coming in too quickly, so it is possible that your computer will freeze up if it cannot keep up with the incoming packets. It would probably be better if you can figure out a way to reduce the number of packets being sent.


Hi Kevin,
Thanks for this great judp contribution.
It seems that when judp needs to receive multiple message that are sent very fast after each other, messages get lost, resulting in a timeout. Would there be a way to 'keep the channel open' in the background and receive all messages?
Messages are sent from the same machine, so that can be really fast.
Thanks in advance for your reply.

Kevin Bartlett

Hi Verena,

If you look in the code, you will see the line:

packet = DatagramPacket(zeros(1,packetLength,'int8'),packetLength);

This is a call to Java code that I "borrowed" from somewhere else, and that I don't fully understand (judp.m is really not much more than a Matlab wrapper for this Java code).

The "int8" format is embedded in this mysterious code; I suppose you could try changing it to 'int16' or whatever, but not being a Java programmer, I don't really know if this would work, or if it would cause other problems.


Verena Müller

I connected two pc with LAN and send from one via UDP packages. With the other one - on which is my matlab script - I receive the data from it. It works very well (thanks for this judp function!). But the problem that I have now is, that I am sending data from a c-programm (integer 16/32 bit) to matlab which uses for the "message-output" mssg an int8 datatyp. So I have an loss of data. How can I change the type of mssg to int16 or an other datatyp?
Thanks in advance!

Kevin Bartlett

@Gus--Good news! I'm gradually learning that it is almost ALWAYS a firewall that is to blame in these situations. Turning off the firewall briefly is a really good test to see if it is the source of a problem.

Gus Lott

Solved. A recent update to McAfee Internet Security resulted in blocking high UDP ports. It did not block TCP ports. JUDP now receives the proper broadcast message. Thanks for your firewall suggestion.

Kevin Bartlett

@Gus--Yes, but the thing doing the sending is sending to, isn't it? Can you change this?

Gus Lott

Not trying to send - just receive the broadcast on port 4992.
mssg = judp('receive',4992,266,3000);
It always times out.

Kevin Bartlett

@Gus--From your Wireshark screenshot ( it looks like you are trying to send to the special broadcast address, ( Have you tried sending to the actual IP address of the destination computer instead of the broadcast address?

Gus Lott

I removed the DAX software that was listening on the same port. Once that was removed, I ran the test you suggested.
I started MATLAB session 1:
mssg = judp('receive',4991,10,5000); char(mssg')
Then execute in MATLAB session 2:
And session 1 shows:
ans =
So loopback is working.
However, WireShark still shows this computer receiving the port 4992 packet I described in the question, but still cannot see it using JUDP.
mssg = judp('receive',4992,266,3000); char(mssg')
Error using judp (line 166)
judp.m--Failed to receive UDP packet; connection timed out.

Kevin Bartlett

@Gus--when you say that "localhost works without an issue", what does that mean? The phrase suggests to me that judp send/receive works as long as you use the loopback address, but that would seem to contradict your first post on July 21. Please clarify.

Gus Lott

Localhost works without an issue. I have not submitted a community question about why I am not seeing a UDP broadcast. See:
Would appreciate any help to discover what's wrong.

Kevin Bartlett

@Gus--I think that BindException means that the port you are trying to use is already taken. Sounds like your "DAX" software is using the same port as judp, which is quite a coincidence. Have you tried using a different port numbers than 21566? It can be any integer between 1025 and 65535, so there are lots to choose from. I guess that still wouldn't explain why you're getting a timeout with DAX disabled, but it might be worth trying.

Gus Lott

Thanks Kevin. Your excellent routine has worked before. Am back to it, and running into issues.

Discovered the problem producing the error given. When the FlexRadio SmartSDR DAX.exe is running, I get the " When I turn it off, receive times out.

With the DAX software disabled, I followed your suggestion. Started this in one session:
mssg = judp('receive',21566,10,5000);
Then immediate did this in another session:

Got this result on the receive session:
Error using judp (line 166)
judp.m--Failed to receive UDP packet; connection timed out.

Will continue troubleshooting. All other software on computer talks TCP & UDP properly.

Kevin Bartlett

@Gus--I don't have access to a 2015 version of Matlab, so I can't really troubleshoot your problem. I will say, though, that the same symptoms could arise from a networking issue or a change in firewall settings. A good test is to have two Matlab sessions running on the same computer. Use one session to send the UDP packet using the "loopback" IP address of Use the other Matlab session to receive the packet. Because the communications are internal to the same computer, this bypasses the network. I'm not sure if this would make a difference, but you could try this test with your computer's firewall off, as well.

Gus Lott

MATLAB Version: (R2015a)
Java Version: Java 1.7.0_60-b19

Has something changed in latest Matlab or Java versions? This used to work, listening on port 4992 for a broadcast.


>> [mssg,sourceHost] = judp('receive',4991,4096,5000)
Error using judp (line 166)
judp.m--Failed to receive UDP packet.
Java error message follows:
Java exception occurred: Address already in use: Cannot bind
at Method)
at Source)
at Source)
at Source)
at<init>(Unknown Source)
at<init>(Unknown Source)
at<init>(Unknown Source)



@Kevin Bartlett
That seems to be the smart way indeed. Thanks

Kevin Bartlett

@exosceleton--My guess would be that Matlab's java machine is not doing garbage collecting properly (I've seen similar problems with Matlab's implementation of database cursor objects). So when you go through 256 IP addresses, you're creating 256 Java Socket objects, and they're clogging up Matlab's allocated Java space and slowing down your computer. As a workaround, why not send a single packet out to your network's broadcast address (see You should be able to use in your call to jupd.m. All the machines on your network will receive the UDP packet, but only the machine you're looking for will know how to respond to the specific UDP packet you send. Once this "handshake" is complete, the two computers will know each other's IP addresses, and you will no longer need to use the broadcast address.


If i enter a static ip of the destination i can send&recieve at a quick rate (multiple cycles per second).

However when i change the ip address in a loop in an attempt to find the the correct device ip in a DHCP environment the cycle time quickly increases to multiple seconds per send&recieve command.

looking for the device from ip takes minutes.

is there a reason for this change in processing time between a fixed ip or multiple ip destinations?



When I send UDP packets using this script, the destination UDP port number stays fixed to the one passed in the argument but source UDP port number seems to be incrementing by 1 every time I call judp. Is there a way to have a fix source UDP port number as well?
Thanks in advance.

Keane Gonzalez

Kevin Bartlett

@Adam: actionStr is an input argument that can be either the string 'send' or the string 'receive'. Have you tried following the examples that are displayed when you type 'help judp'? They should work pretty much as-is, except that when you use 'send', you will have to supply the actual IP address of your target, and in both the 'send' and 'receive' cases, you will need to supply an integer port number between 1025 and 65535. Note that the specified port must be open in the receiving machine's firewall.

Adam Broadhurst

Hi, with regards to the script how would I go about defining the actionStr input argument? Having some trouble getting the script up and running.

Thanks in advance


AMAZING! This code was exactly what I needed for quickly sending small packets between two computers, both sending and receiving. Using test code in a small loop I was able to gt loops that took on average around 10 ms. I couldn't believe it, since the computers I was testing this with were relatively slow.

(p.s. i want to give give code 5 stars, but the website's java isn't working so it won't let me submit my rating.)

Kevin Bartlett

@Victoria--actionStr is an input argument that can be either the string 'send' or 'receive'.

Victoria Emberle

What is actionStr because it is undefined in the version of matlab 2006a

Kevin Bartlett

Sorry, Gabriel, I don't know how a multicast packet differs from a regular UDP packet. Can't you just receive them with judp() like a regular UDP packet?


Hi, thanks for this code. Can you submit a version that supports multicast? I am a novice user at this stuff but really need to read in a UDP multicast packet.


thanks very much for sharing this copy.

Kevin Bartlett

@jawad--If you type "help judp" at the Matlab command line, you should see three simple examples that ought to work as a starting point. The third example is simplest because it uses 'localhost' as the destination for the udp packet; this means you can run both the 'receive' and 'send' judp commands from the same computer (in separate Matlab sessions). Just make sure the specified port, 21566, is open in your firewall.


Can any one guide me how i will be able to run this code step by step.

Allister Kay

Hey. A great programme. I have one remark though. If one has many iterations of the function, let's say in a while-loop receiving realtime udp-packages the socket is opened and closed in every call. This is not criticism, I think an experienced MATLAB programmer will have no problem redesigning the code. BTW, if anyone has a solution for my problem I would be very grateful as my MATLAB skills are limited.

che adil

hello Kiven,
I saw your "judp.m" after having been proposed by a friend to solve a problem of image acquisition of a camera-ip using Matlab.
I wonder if your function "judp.m" able to make this acquisition?
if yes, then how can we do this?
I thank you in advance!

- I work in matlab 2010a
- The camera used is "Teltonika - ip-camera-H264, model: camera3G MVC200

Kevin Bartlett

@Rahul--judp.m is really not that sophisticated a program, so I suspect it is slower than the equivalent command from the Instrument Control Toolbox. The trouble with the Mathworks' UDP/TCP communications programs is that they ARE sophisticated--they may be fast and highly flexible, but they are also very complicated to use (they are also considerably more expensive than judp.m).



Is it faster than the intrument control toolbox command UDP?

Tanyer Alan

Peter Manley-Cooke

Very good. It all works and it provided me with a starting point for what I wanted to do.

Adam Becker

To quickly fix the Ctrl-C issue just add "socket.setReuseAddress(1)"

Jeff Barton

The utility performs exactly as advertised, and is simple to use. (And very timely! It met my needs perfectly.)

The only issue I have noticed is that it (often) does not handle Ctrl-C breaks very gracefully... If I Ctrl-C during a call to judp() to receive a UDP message on a specified port, I can no longer receive on that same port. (I get a "cannot bind" error during subsequent calls to judp() on that same port.) Other than that, great submission!

MATLAB Release Compatibility
Created with R2009a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: TCP/IP Socket Communications in MATLAB

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!