M. Bedross
M. Bedross

Reputation: 129

UDP Communication through Python Doesn't Create Active Internet Connection

I am trying to write a python script that will listen over UDP (arbitrary port 1234) on Ubuntu MATE (running on an Odroid XU-4). For this, I have found code to establish a connection and communicate through it using the python module socket. The code is as follows:

import socket
port = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    s.bind(("localhost", port))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' +  msg[1]
print 'Socket bind complete'
print "waiting on port:", port
while 1:
    data, addr = s.recvfrom(1024)
    print data

This code was not written by myself but is very straight forward. Running this script through the terminal produces no error messages. According to the output, the socket is created and the connection was successful. The trouble that I have is that the tutorial that I got this from says to communicate with this script, opening a client connection through a new terminal will do the trick. Something like:

-$ ncat localhost 1234 -u

Again no error messages, yet. As soon as I try to submit a data packet (plain text, e.g. "test"), I get the error:

Ncat: Connection refused.

In an attempt to troubleshoot myself, I ran a separate terminal window to monitor all UDP connections with root access.

netstat -u

While running the script, I would assume to find port 1234 on the netstat list, but I don't. Meaning that the python script isn't successfully creating and binding to UDP port 1234, but it thinks it is.

Opening the same UDP port using netcat directly through the terminal works, however.

From this, I know that the problem must have something to do with the python script. What could be wrong on the script/python side to not establish a connection, but think that it does?

Thanks in advance!

Upvotes: 0

Views: 518

Answers (2)

M. Bedross
M. Bedross

Reputation: 129

It helps to explicitly define the IP address you wish to connect to. For example:

import socket
IP = "127.0.0.1"
port = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    s.bind((IP, port))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' +  msg[1]
print 'Socket bind complete'
print "waiting on port:", port
while 1:
    data, addr = s.recvfrom(1024)
    print data

Once this is done, connect as a client through netcat like so:

-$ ncat 127.0.0.1 1234 -u

This worked for me, after having the same problem.

Upvotes: 0

Venkata Vamsy
Venkata Vamsy

Reputation: 92

Firstly you can check whether the port is open/closed and then bind. This might help you out:

import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
result = sock.connect_ex(('xxx.xxx.xxx.xxx',1234))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

Upvotes: 1

Related Questions