Just getting started with socket programming, I have created the below code and expecting to print some byte data, but it isn't doing that.
import socket
def create_socket():
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohl(3))
while True:
rdata, address = s.recvfrom(65535)
print(rdata)
It just sits and does nothing.
any directions would be appreciated.
You should have a server where the requests can be sent by the client to print the data
Below is a sample program where you can send message from client and receive the output that was modified by the server
SERVER.PY
from socket import *
serverPort = 12048
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print 'The server is ready to receive'
while 1:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
CLIENT.PY
from socket import *
serverName = '127.0.0.1'
serverPort = 12048
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress =clientSocket.recvfrom(2048)
print modifiedMessage
OUTPUT
SIVABALANs-MBP:Desktop siva$ python client.py
Input lowercase sentence:siva
SIVA
SIVABALANs-MBP:Desktop siva$
EDIT:
Maybe you can try this code
import socket
import struct
import binascii
rawSocket = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.htons(0x0003))
while True:
packet = rawSocket.recvfrom(2048)
ethhdr = packet[0][0:14]
eth = struct.unpack("!6s6s2s", ethhdr)
arphdr = packet[0][14:42]
arp = struct.unpack("2s2s1s1s2s6s4s6s4s", arphdr)
# skip non-ARP packets
ethtype = eth[2]
if ethtype != '\x08\x06': continue
print "---------------- ETHERNET_FRAME ----------------"
print "Dest MAC: ", binascii.hexlify(eth[0])
print "Source MAC: ", binascii.hexlify(eth[1])
print "Type: ", binascii.hexlify(ethtype)
print "----------------- ARP_HEADER -------------------"
print "Hardware type: ", binascii.hexlify(arp[0])
print "Protocol type: ", binascii.hexlify(arp[1])
print "Hardware size: ", binascii.hexlify(arp[2])
print "Protocol size: ", binascii.hexlify(arp[3])
print "Opcode: ", binascii.hexlify(arp[4])
print "Source MAC: ", binascii.hexlify(arp[5])
print "Source IP: ", socket.inet_ntoa(arp[6])
print "Dest MAC: ", binascii.hexlify(arp[7])
print "Dest IP: ", socket.inet_ntoa(arp[8])
print "------------------------------------------------\n"
I could not test the code in my system as AF_PACKET does not work in mac. Try and let me know if in case it works.
Related
i have 2 python programs which speak with sockets.
The First one i have called "King.py":
import os
import time
import sys
import socket
i = 0
s = socket.socket()
host = socket.gethostname()
print("hostname: " + host)
port = 8080
s.bind((host,port))
print("")
print("Auf Verbindungen warten.")
print("")
s.listen(1)
conn, addr = s.accept()
print("")
print(addr, " - Ist dem Server beigetreten.")
print("")
while i < 1:
command = input(str("Command : "))
conn.send(command.encode())
print("Der Befehl wurde gesendet, warte auf Akzeptierung")
print("")
result = s.recv(1024)
result = result.decode()
if result:
print(result)
and the second one i have called "noobie.py":
import time
import sys
import socket
import os
import subprocess
i = 0
s = socket.socket()
host = "realMxrlxn-PC"
port = 8080
s.connect((host, port))
print("")
print(" Connected to server ")
while i < 1:
command = s.recv(1024)
command = command.decode()
if not command == "dir":
os.system(command)
else:
result = subprocess.check_output(command, shell=True)
conn.send(result.encode())
So now i want you to ask why im getting the "WinError 10057" in king.py, because it says i have no socket? (result = s.recv(1024))
I've just started python networking, and after looking at a few internet tutorials, I gave it a go... only problem is, whenever I get a response from the sever, it prints as in:
Recieved from: (Host & Port)b'Hey' - where I haven't put the b anywhere.
Here is the server code:
import socket
import tkinter
import time
import sys
def Main():
top = tkinter.Tk()
top.configure(background='black')
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
con = tkinter.Label(top, text="Connection from: " + str(addr), bg='red', fg='white').pack()
data = c.recv(1024)
if not data:
break
conn = tkinter.Label(top, text="Recieved from: " + str(addr) + str(data), bg='black', fg='white').pack()
top.mainloop()
c.close()
Main()
And my client:
import socket
def Main():
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("> ")
while message != 'quit':
s.send(message.encode('ascii'))
message = input(">")
s.close()
Main()
Thanks for any input - I'm not really good at this yet! (My hosts aren't my computer so that's not the issue)
When you call socket.recv() in Python 3 it returns a bytes object, not a normal string. You can convert it to a normal string as follows:
data.decode('utf-8')
I am learning how to create multithreaded socket server in Python. I used example from some site that I don't remember. I am trying to create simple plugin system but I am not successful. It says that I am passing 3 arguments instead of 2. This is my code:
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
data_sanitized = data.rstrip()
print repr(addr) + ' received: ' + repr(data_sanitized)
from plugins.helloWorld import helloWorld
clazz.fireIt(clientsock,data)#HERE IS THE PROBLEM I THINK
if "close" == data.rstrip(): break
clientsock.close()
print addr, "CLIENT CLOSED CONNECTION"
if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
print 'STARTED SERVER, WAITING FOR CONNECTIONS', PORT
serversock.listen(5)
while 1:
clientsock, addr = serversock.accept()
print 'INCOMING CONNECTION FROM: ', addr
thread.start_new_thread(handler, (clientsock, adde))
and this is my plugin:
from socket import *
def response(key):
return '<response>' + key + '</response>'
class helloWorld():
def fireIt(clientsock,data):
print clientsock
clientsock.send(response(data))
print 'SENDING: ' + repr(response(data))
Thank you
I'm currently trying to write process that embeds a sequence of n IPs into packets and send it off to n server. Each server remove the outermost IP and then forward it to said IP. This is exactly like tunneling I know. During the process I also want the server to do a traceroute to where it's forwarding the packet and send that back to the previous server.
My code currently will forward the packets but it's stuck on performing the traceroute and getting it. I believe it's currently stuck in the while loop in the intermediate server. I think it's having something to do with me not closing the sockets properly. Any suggestion?
Client
#!/usr/bin/env python
import socket # Import socket module
import sys
import os
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 17353 # Reserve a port
FILE = raw_input("Enter filename: \n ")
NIP = raw_input("Enter Number of IPs: ")
accepted_IP = 0
IP= []
while accepted_IP < int(NIP):
IP.append(raw_input("Enter destination IP: \n"))
accepted_IP +=1
#cIP = raw_input("Enter intemediate IP: \n ")
ipv = raw_input("Enter IP version... 4/6")
try:
s.connect((host, port))
print "Connection sucessful!"
except socket.error as err:
print "Connection failed. Error: %s" %err
quit()
raw = open(FILE,"rb")
size = os.stat(FILE).st_size
ls = ""
buf = 0
for i in IP:
while len(i) < 15:
i += "$"
ls += i
header = ipv+NIP+ls+FILE
print ls
s.sendall(header + "\n")
print "Sent header"
data = raw.read(56) +ipv + NIP + ls
print "Begin sending file"
while buf <= size:
s.send(data)
print data
buf += 56
data = raw.read(56) + ipv + NIP + ls
raw.close()
print "Begin receiving traceroute"
with open("trace_log.txt","w") as tracert:
trace = s.recv(1024)
while trace:
treacert.write(trace)
if not trace: break
trace = s.recv(1024)
print "finished forwarding"
s.close()
Intermediate server
#!/usr/bin/env python
import socket
import subprocess
srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
srvsock.bind( (socket.gethostname(), 17353) )
srvsock.listen( 5 ) # Begin listening with backlog of 5
# Run server
while True:
clisock, (remhost, remport) = srvsock.accept() #Accept connection
print
d = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = ""
while True:
b = clisock.recv(1)
if b == "\n":
break
header += b
num = 15 * int(header[1]) + 2
file_name = header[num:]
nheader = header[0]+ str(int(header[1])-1) + header[17:]
d.connect((socket.gethostname(), 12355))
d.sendall(nheader+'\n')
print "begin forwarding"
while True:
raw = clisock.recv(56 + num) # recieve data
ip = raw[-15:] # extract IP
ipv, NIP = raw[57] , str(int(raw[57])-1)
if NIP == "0":
while (raw):
print "stuck in this loop"
d.send(raw[:56])
raw=clisock.recv(56+num)
if not raw: break
else:
while (raw):
print raw[:57] + NIP + raw[59:-15]
print "\n"
d.send(raw[:57] + NIP + raw[59:-15])
raw = clisock.recv(56+num)
if not raw :break
print "Finish forwarding"
d.close()
break
print "Begin traceroute"
tracrt = subprocess.Popen(['traceroute','google.com'], stdout=subprocess.PIPE)
s.sendall(tracrt.communicate()[0])
print "Finished"
clisock.close()
s.close()
Destination server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12355
s.bind((host,port))
s.listen(5)
while True:
csock, (client, cport) = s.accept()
print client
header = ""
while True:
b = csock.recv(1)
if b == "\n":
break
header += b
file_name = header[2:]
r = open("File_test_"+file_name,"wb")
print 'Opening file for writing'
while True:
print "Begin writing file" + " " + file_name
raw = csock.recv(56)
while (raw):
print raw
r.write(raw)
raw = csock.recv(56)
r.flush()
r.close()
print "finish writing"
break
print "closing connection"
csock.close()
s.close()
The intermediate server is stuck in clisock.recv() in this loop because the break condition not raw isn't met before the connection is closed by the client, and the client doesn't close the connection before receiving the traceroute from the intermediate server, so they are waiting on each other.
To remedy this, you might consider sending the file size to the intermediate server, so that it can be used to determine when the receive loop is done. Or, if your platform supports shutting down one half of the connection, you can use
s.shutdown(socket.SHUT_WR)
in the client after sending the file.
I want to send data more than once. I have the following code on server and client:
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
while 1:
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
s.close
I send the first string, get the response, but when I send the second string, it hangs.
How can I solve this?
Here is the code that worked
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
while 1:
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()
This my client and it's working.
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()