Python UDP networking socket.error: [Errno 10049] - python-2.7

I am trying to establish a simple UDP connection using Python code, between 2 PCs through internet.
Code run on PC_1:
import socket
import time
HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
code run on the 2nd PC:
import socket
HOST = "ip_address_of_PC1"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
While running the code on 2nd PC am getting following error message:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context

change print s.recv(30) to:
data, addr = s.recvfrom(30)
print data
and in the 2nd PC code, the HOST variable needs the value of the 2nd PC ip, not the first one:
HOST = "ip_address_of_PC2"

Code run on PC1:
import socket
import time
HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
Code run on PC2:
import socket
HOST = "private ip_address_of_PC2"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)

Related

How do I loop ports to scan?

I have this problem with a portscanner which keeps hanging at scanning port 1. How can I solve this problem?
#! /usr/bin/env python
import socket
import subprocess
from datetime import datetime
#Clear the screen
subprocess.call('clear', shell=True)
def portscan():
server = raw_input("Enter the server to scan: ")
serverIP = socket.gethostbyname(server)
# Printing banner with information about host
print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
print "[!] Please wait, scanning for open services...\n"
#Time when scan started.
t1 = datetime.now()
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((serverIP, port))
if result == 0:
print "[+] Port {}: Status:OPEN\n".format(result)
sock.close()
except socket.gaierror:
print "Hostname could not be resolved, Exiting...\n"
sys.exit()
except socket.error:
print "Couldn\'t connect to server, Exiting\n"
sys.exit()
#Checking time again
t2 = datetime.now()
#Calculate duration of scan
totaltime = t2 - t1
print "Scan completed, duration: {}\n".format(totaltime)
What happens when i run it i give it a hostname and resolve it to a IP
Address but whenever the scan starts it keeps scanning port 1 as i saw
in Wireshark
I think that you maybe need a timeout.
Eventually, your sock.connect_ex( ), will to raise an exception socket.error: [Errno 110] Connection timed out, as you can read more about it, in this answer.
But the default timeout could be 120 seconds, and maybe you don't want to wait so much. So, you can set your own timeout, like that:
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10) #timeout set for wait up 10 seconds.
result = sock.connect_ex((serverIP, port))
sock.settimeout(None)
To know why to use sock.settimeout(None), and see another ways of setting timeout, you can read this discussion.
I'm not sure if it was what you're looking for, but I hope it may help.

How to send a captured packet saved as text with Python

I captured packets on individual text files with tcpdump, I want to send back the captured packets, first I extracted the IP and Port, but I have not been able to send the packet.
This is my code:
def client():
packet = open("packet3.txt", "r")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("192.168.128.1", 80))
while True:
try:
sock.send("packet")
sleep(1)
reply = sock.recv(131072)
if not reply:
break
print "recvd: ", reply
except KeyboardInterrupt:
print "bye"
break
sock.close()
return
client()
I get this error:
reply = sock.recv(131072)
error: [Errno 10054] An existing connection was forcibly closed by the remote host

Python Client is unable to receive data sent from Python Server

I am trying to send some data from my python client to python server
I have followed this link
My python client code is as follows
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '10.4.1.25';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((host , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = "16973"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
the python server code is
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
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'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
conn.close()
s.close()
The Function sendall is used to send data to client , means when I enter the text in terminal on server I should see it on client as well. But this does not happen
The output which I get is
Server Output
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656
Client Output
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I am unable to know what's going wrong here?
Also how can I send data (message) from Python Client to Python server??
Any help would be great !
Thanks!

Receive code not working XBee python

Configured two xbee pro s2b using X-CTU, one as coordinator and other as router, API=2, baudrate as 9600. The sender code (coordinator) is as below:
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB0"
BAUDRATE = 9600
#open serial port
sender_port = serial.Serial(PORT, BAUDRATE)
print "serial port object>>>", sender_port
#xbee object API=2
sender = XBee(sender_port,escaped=True)
#address of the remote xbee to which data is to sent
ADDRESS = "\x00\x13\xA2\x00\x40\xD9\x6F\xE5"
#send data using the tx_long_addr
while True:
try:
print "sending data..."
sender.tx_long_addr(frame_id='A', dest_addr=ADDRESS, data="hello")
time.sleep(1)
except KeyboardInterrupt:
break
sender.halt()
sender_port.close()
below is the receiver code (router)
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB1"
BAUDRATE = 9600
def byte2hex(byteStr):
return ''.join(["%02X" % ord(x) for x in byteStr]).strip()
def decodereceivedFrame(data):
source_address = byte2hex(data['source_addr'])
xbee_id = data['id']
rf_data = data['rf_data']
options = byte2hex(data['options'])
return [source_address, xbee_id, rf_data, options]
#open serial port at receiving end
remote = serial.Serial(PORT, BAUDRATE)
#xbee object API=2
remote_xbee = XBee(remote, escaped=True)
while True:
try:
print "yes i m here"
data = remote_xbee.wait_read_frame()
print "data >>>", data
decoderdata = decodereceivedFrame(data)
print "data received<<<<", decoderdata
except KeyboardInterrupt:
break
remote_xbee.halt()
remote.close()
But on executing the receiver code, nothing happens, it does not print the received message. On X-CTU frames are being transmitted and received without any errors, am i doing something wrong in the code. Please guide .
Thank you
Found the issue, my fault----
sender = ZigBee(sender_port, escaped=True)
sender.send('tx', frame_id='A', dest_addr="\x5E\x71", dest_addr_long="\x00\x13\xA2\x00\x40\xD9\x6F\xE5", data="Hello")
Works now ..!!! :)

How can I get the port used to make a socket connection in Python 2.7?

I am making a IRC Client script to learn a bit about Python, that may evolve down the road... So I can connect with out issue. But I want to get the port that the socket connection is using when I use socket.connect() .
I ask, because I want to compile with the Auth RFC.
So I want to be able to send,
MYPORT, SERVPORT : USERID : Windows : Username
Is it possible to get the port of the socket being used for the out going connection? So something like this:
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect(('irc.rizon.net', 6667))
irc.send( str( irc.getsocketused() ) + ", 6667 : USERID : Windows : Username")
You can use the getsockname method on the socket, for example for IPv4;
>>> irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> irc.connect(('irc.rizon.net', 6667))
>>> addr,port = irc.getsockname()
>>> port
52675 (this will be your local port)