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)
Related
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
everyone, i'm using a python code to Stream voice between to endpoints.
the code doesn't give me an error i just stuck at some point i don't now why
what im trying to achieve is i want to speak from one endpoint and hear my voice at the other end point
i don't want to use TCP i want to use UDP so i can avoid the latency
the receiver cod
import socket
import pyaudio
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
audio = pyaudio.PyAudio()
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.connect(("172.20.10.6", 5555))
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=CHUNK)
#while True :
#print("Enter a UDP M\n")
#MESSAGE = input("")
#sock.sendto(MESSAGE.encode('utf-8'), (UDP_IP, UDP_PORT))
try:
while True:
data = sock.recvfrom(CHUNK)
stream.write(data)
except KeyboardInterrupt:
pass
print('Shutting down')
sock.close()
stream.close()
audio.terminate()
the sender
import pyaudio
import socket
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
audio = pyaudio.PyAudio()
UDP_IP = "0.0.0.0"
UDP_PORT = 5555
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM , socket.IPPROTO_UDP) # UDP
sock.bind((UDP_IP, UDP_PORT))
def callback(in_data, frame_count, time_info, status):
for s in read_list[1:]:
print (s)
s.send(in_data)
return (None, pyaudio.paContinue)
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback)
# stream.start_stream()
read_list = [sock]
print ("recording...")
try:
while True:
print ("1")
readable, writable, errored = select.select(read_list, [], [])
print ("2")
for s in readable:
if s is sock:
(clientsocket, address) = sock.accept()
read_list.append(clientsocket)
print ("Connection from", address)
else:
data = sock.recvfrom(1024)
if not data:
read_list.remove(s)
except KeyboardInterrupt:
pass
print ("finished recording")
serversocket.close()
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
as you can see the code stuck at where i print the number 2 it doesn't print it
the below code is to a UDP connection that only Send a String
import socket
UDP_IP = "172.20.10.6"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
while True :
print("Enter a UDP M\n")
MESSAGE = input("")
sock.sendto(MESSAGE.encode('utf-8'), (UDP_IP, UDP_PORT))
import socket
UDP_IP = "172.20.10.6"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", data)
I tried to send message to server from client with manual input, with 10 limits input. its succesfully work on client side but when i tried to run server it's shows nothing
here's the code from client side
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
else :
print("lebih dari 10!!")
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
s.close()
here's result and code from server side
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
while True:
data, address = s.recvfrom(1024)
print(data)
print(address)
s.close()
when i run the program, nothing happen. here's the running program
Your main problem is the else statement you added there which is not executing. If want to put a limit of 10 after accepting the input, you are supposed to print the statement after the loop.
This is the client code:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
print("lebih dari 10!!")
s.close()
Edit:
I am not really understanding your problem but as far as I understand you want to show the limit on the server. Thus you can do this, try adding a loop on the server and receive input from the client's address only to avoid receiving extra messages.
Server Code:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
x = 0
while True:
data, address = s.recvfrom(1024)
# This block will make sure that the packets you are receiving are from expected address
# The address[0] returns the ip of the packet's address, address is actually = ('the ip address', port)
if address[0] != '127.0.0.1':
continue
# The logic block ends
print(data)
print(address)
x = x + 1 # This shows that one more message is received.
if x == 10:
break # This breaks out of the loop and then the remaining statements will execute ending the program
print("10 messages are received and now the socket is closing.")
s.close()
print("Socket closed")
I have commented the code so I hope you understand the code
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")
Linux Kernel offers a few ways to get timestamps for received (SO_TIMESTAMP, SO_TIMESTAMPNS, SO_TIMESTAMPING) or sent (SO_TIMESTAMPING) packets.
Kernel Doc: https://www.kernel.org/doc/Documentation/networking/timestamping.txt
Is there a way I can use that with Python? I don't see any SO_TIMESTAMP constant inside the Python sources. Tried 3.6.2 and GitHub master branch.
Right now, I can only use SIOCGSTAMP that gives me the timestamp of the last received packet and nothing seems available for sent packet timestamp.
Finally, I have been able to get the SO_TIMESTAMPNS value like this:
SO_TIMESTAMPNS = 35
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
s.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
raw_data, ancdata, flags, address = s.recvmsg(65535, 1024)
ancdata[0][2] is the hardware timestamp as a timespec(ulong, ulong).
Does work on Linux but not on Mac OS X. Not tested on Windows.
complete code, send and receive using python3
import struct
import time
import select
import socket
import sys
if(len(sys.argv)!=2):
print("usage: ",sys.argv[0]," <send|receive>")
sys.exit()
print(sys.argv[1]);
if(sys.argv[1]=='send'):
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect(('localhost', 10000))
s.send(MESSAGE)
time.sleep(0.0001)
#time.sleep(5)
s.send(MESSAGE)
s.close()
else:
SO_TIMESTAMPNS = 35
#s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
server.bind(('localhost', 10000))
server.listen(5)
inputs = [ server ]
message_queues = {}
outputs = []
while inputs:
print('\nwaiting for the next event')
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
print('new connection from', client_address)
connection.setblocking(0)
inputs.append(connection)
else:
raw_data, ancdata, flags, address = s.recvmsg(65535, 1024)
print('received ', raw_data, '-',ancdata,'-',flags,'-',address)
if(len(ancdata)>0):
#print(len(ancdata),len(ancdata[0]),ancdata[0][0],ancdata[0][1],ancdata[0][2])
#print('ancdata[0][2]:',type(ancdata[0][2])," - ",ancdata[0][2], " - ",len(ancdata[0][2]));
for i in ancdata:
print('ancdata: (cmsg_level, cmsg_type, cmsg_data)=(',i[0],",",i[1],", (",len(i[2]),") ",i[2],")");
if(i[0]!=socket.SOL_SOCKET or i[1]!=SO_TIMESTAMPNS):
continue
tmp=(struct.unpack("iiii",i[2]))
timestamp = tmp[0] + tmp[2]*1e-10
print("SCM_TIMESTAMPNS,", tmp, ", timestamp=",timestamp)
if(not raw_data):
print('closing after reading no data')
# Stop listening for input on the connection
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()