i have this code to read a msg from a client.
import socket
# UDP_IP = 'fd53:7cb8:383:2::10'
UDP_IP = '::'
UDP_PORT = 13400
# create socket
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# bind the socket
server_add = (UDP_IP, UDP_PORT)
print('starting up on {} on port {}'.format(*server_add))
sock.bind(server_add)
while True:
print('waiting msg')
data, addr = sock.recvfrom(1024)
print("received message:", data)
print("addr is", addr)
sock.close()
break
the client IP is : 'fd53:7cb8:383:2::c9'
the Server IP is : 'fd53:7cb8:383:2::10'
i can saw the msg on wireshark
No.
Time
Delta
Source
Destination
Protocol
Length
70
6.516768
3.631930
fd53:7cb8:383:2::c9
ff02::1
DoIP
103
but the sock.recvfrom(1024) is not getting anything
Related
I am hosting a server listening for UDP packets on local host with IP address '127.0.0.1'. On the same machine, how would I be able to send packets to this server with spoofed IP address '1.2.3.4' and not '127.0.0.1'?
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
sizes = {}
for size in range(512):
sizes[size] = 0
while True:
data, addr = sock.recvfrom(8092)
if addr[0] != "1.2.3.4":
print("Acess denied")
#print(addr[0])
#print(len(data))
continue
else:
print("hello")
print ("length:", len(data))
sizes[len(data)] += 1
Currently this is the code I am using to send UDP packets.
import socket
import ipaddress
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
if __name__ == "__main__":
ipaddress.ip_address(unicode('1.2.3.4', "utf-8"))
Message = "H"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP, UDP_PORT))
I have a correct code. Everything seems okay but it is not capturing any data packets:
UDP_PORT = 0
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM ) # UDP
sock.bind(('', 0))
print("waiting on port:", UDP_PORT)
while True:
data, addr = sock.recvfrom(65565) # buffer size is 1024 bytes
print ("received message:", data)
I have a listener on a tcp localhost:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def client_socket():
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1:
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
s.close()
I am trying to send a JSON object to the same port on the local host:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender' : local_ip,
'instruction' : direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data)
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data)
data = s.recv(1024)
print('Received', repr(data))
However, I get a socket error:
socket.error: [Errno 98] Address already in use
What am I doing wrong? Will this work or do I need to serialize the JSON object?
There are a few problems with your code, but the one that will likely address your issue is setting the SO_REUSEADDR socket option with:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
after you create the socket (with socket.socket(...) but before you attempt to bind to an address (with s.bind().
In terms of other things, the two "halves" of the code are pretty inconsistent -- like you copied and pasted code from two different places and tried to use them?
(One uses a context manager and Python 3 print syntax while the other uses Python 2 print syntax...)
But I've written enough socket programs that I can decipher pretty much anything, so here's a working version of your code (with some pretty suboptimal parameters e.g. a buffer size of 1, but how else would you expect to catch a single ;?)
Server:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
BUFFER_SIZE = 1
def server_socket():
data = []
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen()
while 1: # Accept connections from multiple clients
print('Listening for client...')
conn, addr = s.accept()
print('Connection address:', addr)
while 1: # Accept multiple messages from each client
buffer = conn.recv(BUFFER_SIZE)
buffer = buffer.decode()
if buffer == ";":
conn.close()
print("Received all the data")
for x in data:
print(x)
break
elif buffer:
print("received data: ", buffer)
data.append(buffer)
else:
break
server_socket()
Client:
import socket
import json
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender': local_ip,
'instruction': direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data + ";")
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data.encode())
data = s.recv(1024)
print('Received', repr(data))
json_message("SOME_DIRECTION")
this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()
Someone can add to my Example under, the code that define the Client socket try to connect to the server for 2 seconds please ?
I read about that and i don't successful to do that, because of that i ask for an example.
Example:
Client:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Server:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 20
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()
Thank you.
Instead of having two separate python files, you can have a single file but put the server and client in separate threads. sys.stdout.write is used instead of print due some concurrency issue with print being buffered (it mixes strings).
import threading
import socket
import sys
class socket_server(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 20
daemon = True
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.TCP_IP, self.TCP_PORT))
s.listen(1)
conn, addr = s.accept()
(ip, port) = addr
sys.stdout.write("%s connection address: IP %s on Port %d\n" % (self.__class__.__name__, ip, port))
data = True
while data:
data = conn.recv(self.BUFFER_SIZE)
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
send_data = data.upper()
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, send_data))
conn.send(send_data)
conn.close()
class socket_client(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 1024
TIMEOUT = 2.0
MESSAGE = "Hello, World!"
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.TIMEOUT)
s.connect((self.TCP_IP, self.TCP_PORT))
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, self.MESSAGE))
s.send(self.MESSAGE)
data = s.recv(self.BUFFER_SIZE)
s.close()
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
server = socket_server()
client = socket_client()
server.start()
client.start()