udp clientserver

*msg) perror(msg); exit(EXIT_FAILURE);

sockfd; sockfd = socket(AF_INET,SOCK_DGRAM,0);

sockaddr_in serv,client; serv.sin_family = AF_INET; serv.sin_port = htons(53000); serv.sin_addr.s_addr = inet_addr(

; fgets(buffer,256,stdin); sendto(sockfd,buffer,

sockaddr *) recvfrom(sockfd,buffer,256,0,(

*msg) perror(msg); exit(EXIT_FAILURE);

sockfd; sockfd = socket(AF_INET,SOCK_DGRAM,0);

sockaddr_in serv,client; serv.sin_family = AF_INET; serv.sin_port = htons(53000); serv.sin_addr.s_addr = inet_addr(

this is the first time i am doing socket programming…this is compiling and running but there is no comunication between the socket and client..

The real problem is that the server isnt binding to an address. As a result, the client cant connect to it.

that has address INADDR_ANY (to bind to all IP4 network interfaces), then use that address with bind().

Youre not specifying the network protocol when you create the socket. You may or may not get away with it. The actual value in this case should be IPPROTO_UDP, not zero.

Programming udp sockets in python

UDP or user datagram protocol is an alternative protocol to its more common counterpart TCP. UDP like TCP is a protocol for packet transfer from 1 host to another, but has some important differences. UDP is a connectionless and non-stream oriented protocol. It means a UDP server just catches incoming packets from any and many hosts without establishing a reliable pipe kind of connection.

In this article we are going to see how to use UDP sockets in python. It is recommended that you also learn aboutprogramming tcp sockets in python.

The SOCK_DGRAM specifies datagram (udp) sockets.

Since udp sockets are non connected sockets, communication is done using the socket functions sendto and recvfrom. These 2 functions dont require the socket to be connected to some peer. They just send and receive directly to and from a given address

The simplest form of a udp server can be written in a few lines

import socket port = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((, port)) print waiting on port:, port while 1: data, addr = s.recvfrom(1024) print data

A udp server has to open a socket and receive incoming data. There is no listen or accept. Run the above server from a terminal and then connect to it using ncat. Ncat is a telnet alternative that is more powerful and more featureful.

The u flag indicates the udp protocol. Whatever message we send, should display on the server terminal.

Lets write a complete echo server now.

Simple udp socket server import socket import sys HOST = Symbolic name meaning all available interfaces PORT = 8888 Arbitrary non-privileged port Datagram (udp) socket try : s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print Socket created except socket.error, msg : print Failed to create socket. Error Code : + str(msg[0]) + Message + msg[1] sys.exit() Bind socket to local host and port try: s.bind((HOST, PORT)) except socket.error , msg: print Bind failed. Error Code : + str(msg[0]) + Message + msg[1] sys.exit() print Socket bind complete now keep talking with the client while 1: receive data from client (data, addr) d = s.recvfrom(1024) data = d[0] addr = d[1] if not data:  break reply = OK… + data s.sendto(reply , addr) print Message[ + addr[0] + : + str(addr[1]) + ] – + data.strip() s.close()

The above will program will start a udp server on port 8888. Run the program in a terminal. To test the program open another terminal and use the netcat utility to connect to this server. Here is an example

Use ncat again to send messages to the udp server and the udp server replies back with OK… prefixed to the message.

The server terminal also displays the details about the client

It is important to note that unlike a tcp server, a udp server can handle multiple clients directly since there is no connection. It can receive from any client and send the reply. No threads, select polling etc is needed like in tcp servers.

Now that our server is done, its time to code the udp client. It connects to the udp server just like netcat did above.

udp socket client Silver Moon import socket for sockets import sys for exit create dgram udp socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print Failed to create socket sys.exit() host = localhost; port = 8888; while(1) : msg = raw_input(Enter message to send : ) try : Set the whole string s.sendto(msg, (host, port)) receive data from client (data, addr) d = s.recvfrom(1024) reply = d[0] addr = d[1] print Server reply : + reply except socket.error, msg: print Error Code : + str(msg[0]) + Message + msg[1] sys.exit()

The client will connect to the server and exchange messages like this

$ python simple_client.py Enter message to send : hello Server reply : OK…hello Enter message to send : how are you Server reply : OK…how are you Enter message to send :

Overall udp protocol is simple to program, keeping in mind that it has no notion of connections but does have ports for separating multiple udp applications. Data to be transferred at a time should be send in a single packet.

Subscribe to get updates delivered to your inbox

Php developer, blogger and Linux enthusiast.

He can be reached at[emailprotected]om.

hey can you correct my code sir??

its about 350 lines biga client side program

but with very few errors of sockets only

how can i broadcast the message to all clients when they are connected to this server ???

hey.. nice tutorial but this doesnt work for a client and server running in two different systems shared over a wifi. should we change the protocol for doing the same?

Would your code run for python 3.x (after normal changes like print())???

I am running your first simple block of code at the top of this tutorial in the python IDE, I also tried it through a terminal, both on win7. The code runs fine, but when I try to connect via telnet, ncat or putty, I get the following:

On windows telnet I get this error: Could not open connection to the host, on port (tried lots), connect failed

with ncat I get: An existing connection was forcibly closed by the remote host. .

and with putty I get: Network error: connection refused

Also, I went through your tcp socket tutorial, and that all worked correctly. Any help much appreciated.

Im getting the same error here, any advice?

Both protocols, Telnet and SSH work on TCP.

msg = raw_input(Enter message to send : )

Sorry, when i run it, it has a problem with raw_input like that:NameError: name raw_input is not defined

Whats statement you define it in your source???

In python 3 raw_input has been renamed to input. So use input.

Thank a lot. I try to using python 3.3 with your project.

Can i import it from 2.x to 3.x with this project.

TypeError: str does not support the buffer interface

I think its wrong in s.sendto() @@

Yeah, it should be easy to port the program to python 3+

You have to do a couple of changes like wrapping print statements in brackets like a function etc.

There is only some syntax change to be done.

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print (Failed to create socket)

msg = input(Enter message to send : )

receive data from client (data, addr)

print (Server reply : + reply)

print (Error Code : + str(msg[0]) + Message + msg[1])

is that true?? but it doesnt work @Silver Moon

But in this Server has other[emailprotected]@ Im so sorry, because im a newbie

Silver Moon ([emailprotected])

HOST = Symbolic name meaning all available interfaces

PORT = 8888 Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print (Socket created)

print (Failed to create socket. Error Code : + str(msg[0]) + Message + msg[1])

Bind socket to local host and port

print (Bind failed. Error Code : + str(msg[0]) + Message + msg[1])

print (Socket bind complete)

receive data from client (data, addr)

reply = OK + data.decode(utf-8)

s.sendto(reply.encode(utf-8) , addr)

print (Message[ + addr[0] + : + str(addr[1]) + ] + data.strip())

print (Message[ + addr[0] + : + str(addr[1]) + ] + data.strip().decode(utf-8))

Youre a good one!!! Thank again!!!

Mail (will not be published) (required)

C UDP Multicasting Tutorial

Learn how to use a UDP Multicast in c to quickly send data from one machine to a next. This method is commonly refered to as a UDP rendezvous.(yes probably why Tibcos product that does this is called rendezvous)

This tutorial will consist of two programs:

Server (Sender) a console app that is responsible for sending messages

Client (Listener) a console app that is responsible for recieving messages

The reason they are both console apps is to keep things simple.

Before we jump into the code there are a few things that you need to know.

Technically multicasting addresses must be between 224.0.0.0 to 239.255.255.255, but 224.0.0.0 to 224.0.0.255 is reserved for routing info so you should really only use 224.0.1.0 to 239.255.255.255.

For the port number you can choose anything you like but its best do investigate the port you choose a bit so you dont conflict with something already using that port. A good place to look iswikipedia

The server must make a connection to our multicast address and then join our multicast group. By joining the group we can add content to it, which gets delivered to anyone else in the group.

IPAddress multicastaddress = IPAddress.Parse(239.0.0.222); udpclient.JoinMulticastGroup(multicastaddress); IPEndPoint remoteep = new IPEndPoint(multicastaddress, 2222);

Really that is it. The rest is just to encode the message and send it like so:

Byte[] buffer = null; for (int i = 0; i = 8000; i++) buffer = Encoding.Unicode.GetBytes(i.ToString()); udpclient.Send(buffer, buffer.Length, remoteep); /csharp Now because this is a Console app we can add a new messages in there to see whats going on. The complete class looks like this: csharp using System; using ; using System.Net.Sockets; using System.Text; namespace Jarloo.Sender internal class Program private static void Main(string args) UdpClient udpclient = new UdpClient(); IPAddress multicastaddress = IPAddress.Parse(239.0.0.222); udpclient.JoinMulticastGroup(multicastaddress); IPEndPoint remoteep = new IPEndPoint(multicastaddress, 2222); Byte buffer = null; Console.WriteLine(Press ENTER to start sending messages); Console.ReadLine(); for (int i = 0; i = 8000; i++) buffer = Encoding.Unicode.GetBytes(i.ToString()); udpclient.Send(buffer, buffer.Length, remoteep); Console.WriteLine(Sent + i); Console.WriteLine(All Done! Press ENTER to quit.); Console.ReadLine(); /csharp h2UDP Multicasting C Client (Listener)/h2 Like the server the client must also connect to the multicast group UdpClient client = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222); client.Client.Bind(localEp); IPAddress multicastaddress = IPAddress.Parse(239.0.0.222); client.JoinMulticastGroup(multicastaddress);

Notice the code looks very similiar to the sender we created except that we bind to an endpoint. This is necessary as we will be listening for incoming data.

So now that were connected we just need to listen for messages and do something with them.

Yes that is an infinate loop. (this is just for demonstration purposes remember?) To close this client down you will have to kill it. Yes there are easier ways including sending a quit message from the server etc.. etc.., but I didnt want to add a bunch of code that would confuse things here.

Also important to note is that the client.Receive call is blocking. This means that code execution will halt on that line until a message is received. So if you do something similiar in your own programs you would either want this on a different thread or you would want to use the async methods instead. (Async methods are best because if you multi-thread it, to stop the client you will need to interrupt the thread which will throw an exception.)

One issue youll discover is that you can only have a single listener working on a machine at a time. This is because the port is set for exclusive use. So if you want multiple Listeners on a single machine you will need to change this by doing this:

client.ExclusiveAddressUse = false; IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false;

This would go right under the creation of the UdpClient.

The complete code the Listener looks like this:

using System; using llections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace Jarloo.Listener internal class Program private static void Main(string[] args) UdpClient client = new UdpClient(); client.ExclusiveAddressUse = false; IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; client.Client.Bind(localEp); IPAddress multicastaddress = IPAddress.Parse(239.0.0.222); client.JoinMulticastGroup(multicastaddress); Console.WriteLine(Listening this will never quit so you will need to ctrl-c it); while (true) Byte[] data = client.Receive(ref localEp); string strData = Encoding.Unicode.GetString(data); Console.WriteLine(strData);

UDP Multicasting is a great way to send around data but there are a few things to look at to determine if this method is right for you.

Requires no dedicated server. Your client and server can be the same app, making this a very nice distributed solution with no single point of failure.

Fast. Very, very fast. Since there are no extra jumps to servers and translation etc the code executes very fast.

Messages are not guaranteed. They can be lost, so if your passing around something critical like banking transactions this wouldnt be a good idea.

Common uses for this style of architecture are in places where data is updating very quickly and each message sent has a very short lifespan. You see this being used in trading shops quite a bit for sending prices. If a single price is lost, its not that big of a deal because another one will follow in seconds.

If your looking to route data to multiple machines the problem has been tackled before, and there are some great open source projects that work very well and can help. Two I would recommend are:

RabbitMQ This is the easiest setup for a queuing system I have seen, and it once you get it up and running it just works without issue. Ive been using this in a production scenario for over a year and am very happy with it. Used to use ActiveMQ but Ive found this much better and more reliable.

I have aRabbitMQ Tutorialif your interested.

ZeroMQ This one I havent personally used yet, but it sounds very good and it created to be extremely low latency.

Hope you enjoyed this tutorial, if I get the time Ill post an Async version of this.

Sorry, comments are closed for this item.

Enter your email address to subscribe and receive notifications of new posts by email.