How to send a captured packet saved as text with Python - python-2.7

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

Related

Store data that would be sent over the socket when it disconnects and manage it when socket reconnects

I have a problem where I need to store data on a disk when the TCP socket disconnects for whatever reason that would otherwise be sent over that socket and simultaneously check when a new connection is established and I can't find a solution to this.
What I have is:
def start_server_for_clients(srv, port):
client = None
try:
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(('', port))
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.listen(5)
print('Waiting for clients on port %s' % port)
while True:
client, address = srv.accept()
client.settimeout(10)
print('Connected client %s %s.' % (address[0], address[1]))
t = threading.Thread(target=handle_client, args=(client, address))
t.daemon = True
t.start()
except Exception as e:
print(e)
if client:
client.close()
handle_client is a function where data is processed and sent over the socket every second in a while loop. I need that processed data either way: connected or not and store it.
Now my logic to separate data processing and socket communication into different parts but where does it fit into threading once the connection is back up again because I would need to clear off the stored data first while simultaneously storing/buffering newly accumulated data and only then proceed to instant communication between sockets? Do I need to use select in this thread and spawn another one to for storing and recovering?

Python UDP networking socket.error: [Errno 10049]

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)

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!

server socket error timer management

There is a server for a single client. Client can connect and disconnect at any time
Here is simplified code
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while true:
a = s.accept()
try:
data = a[0].recv(1024)
except socket.error:
a[0].close()
print 'cought the error'
It works, but socket.error generation takes random amount of time from few seconds up to a minute. May this value be managed?
If the client disconnects, there is no socket.error, rather recv() returns an empty string immediately. Besides, you are not closing the connection in this case.

Web Server: socket programming for TCP connections in Python

I'm trying to run a python web server. The server says is running so I assume it is all working, except that I can only see the html text. The jpeg/image and the pdf files won't dispaly. Here is what i have so far.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 12000))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'Required connection', addr
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send('404 Not Found')
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
I'm working on the same thing. I added the line:
connectionSocket.send('Content-Type: image/jpeg')
right after this:
connectionSocket.send('HTTP/1.0 200 OK')
I assume I'm/we're just missing some line in the header.