Enabling ethernet connection between Teensy 4.1 and intel-NUC - sockets

I am trying to establize socket connection between Teensy 4.1 and intel-NUC(Using Ubuntu) directly.
What I tried :
I have connected Teensy 4.1 to my local ethernet switch where my PC and intel-NUC both are connected via ethernet cable. I was able to perform UDP socket communication in between teensy to PC and teensy to NUC both. All works fine.
Problem :
(I am frm electronics background and know very little about networking.)
I dont want to use a switch so I tried to connect Teensy with NUC directly via ethernet cable and the same code doesnt work anymore.
Is it even possible ?
Do I have to make some changes for this to work ?
Teensy is programmed into arduino and in NUC I am using python. Python code I am sharing below.
import socket
UDP_IP = "192.168.10.8" (IP of Teensy)
UDP_PORT = 12345
MESSAGE = b".."
print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print("received message: %s from" % data,end="")
print(addr)
break

Related

How do game clients receive UDP data from server?

What I wanted to do:
For learning about game programming I created an echo setup using a dedicated server and UDP. The dedicated server is in a different city (aka NOT in my local network).
On my local computer I have a udp client and server ( 2 different programs ). When I first started my python server I was immediately asked by windows firewall whether I want to add an exception. After allowing networking for my python server, I still did not receive any messages. (client -> dedicated server -/-> local server )
Only after I set a port forwarding in my router I was able to receive messages on my local UDP server.
My question is:
How do games solve that problem ? I don't activate a port forwarding for each multiplayer game I want to play and I'm still able to receive data in all these games.
My dedicated server setup (address and port intentionally changed):
#!/usr/bin/python3
import socket
ADDRESS = "1.123.123.123"
PORT = 12345
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((ADDRESS, PORT))
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
addresses = []
while True:
data, addr = serverSock.recvfrom(1024)
if addr not in addresses:
addresses.append(addr)
msg = str(data)
#if msg.split()
print("Message: " + str(data))
outMsg = str(addr) + ":" + msg
for ad in addresses:
print("Send Msg " + outMsg + " to " + ad[0] + ":" + str(PORT))
clientSock.sendto(bytes(outMsg, "utf-8"), (ad[0], 12345))
print("Addresses: " + str(addresses))
I figured this one out while writing up the question (like talking to the good old rubber duck):
The trick is not using 2 programs on the local computer. The program that sends the message also needs to retrieve the message. In my example it's blocking calls (ugly!), for a game you'd want to make that asynchronous. But this is the simplest way to get around the router firewall:
#! /usr/bin/python3
import socket
ADDRESS = "1.123.123.123"
PORT = 12345
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# usually not required to bind a client, but we want to receive messages
clientSock.bind(("0.0.0.0",PORT))
while True:
msg = input("Enter message: ")
# Note that it is not required to send to the same port
# you have locally binded to.
clientSock.sendto(bytes(msg, "utf-8"), (ADDRESS, PORT))
# listen to the echo:
data, addr = clientSock.recvfrom(1024)
print(str(data) + " from " + str(addr))
However, my understanding on sockets and firewalls is limited. I do not understand why THIS works but 2 separated programs don't. Maybe someone could comment on that.
Hope I can save someone some time =)

Multicast between server and client with or without a router not knowing server IP in advance and possible diferent sub-net

I'm writing in Python software that runs on my Windows (and Linux) PC, while the PC is connected via LAN (with or without a router) to a second device.
The second device sends UDP multicast packets to a known multicast group address and port.
The software in the computer is configured to be part of the same multicast group.
This is working OK as long as both my computer and the server network configuration are on the same sub-net.
Now, most of the times I will don't know the IP of the device in advance and I'll be connecting my computer directly to the server point-to-point. (Imagine the software that comes with IP security cameras that allows you to discover or know the IP of the camera when connecting directly to them with out knowing it in advance and without being in the same sub-net). E.g my computer has IP 169.x.x.x/24 and the server has IP 10.1.1.100 but I do not know the server IP in advance.
For reasons out of my control, the device cannot be configured to be a DHCP server so it cannot assign IP to my computer and cannot use DNS.
How can I receive the UDP multicast packets without raw capture?
This is my current code for the socket configuration that is working when both the computer and the server have the same sub-net. Ex 10.1.1.100/16 and 10.1.1.60/16 but needs to work also as mentioned above.
class MulticastSocket(object):
"""Sends UDP packets to multicast addressses."""
def __init__(self, bind_ip=None):
self._create(bind_ip)
def _create(self, bind_ip):
self.bind_addr = bind_ip
# chosen arbitrary from IANA's Scoped Multicast Range
# https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#unicast-prefix-based
self.multicast_group = '239.6.2.86'
self.multicast_port = 6286
"""Creates a multicast UDP socket"""
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self._sock.settimeout(6)
ttl = 2
self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
self._sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.bind_addr))
membership_request = struct.pack('4s4s', socket.inet_aton(self.multicast_group),
socket.inet_aton(self.bind_addr))
self._sock.setsockopt(
socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership_request)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if sys.platform == 'linux':
bind_addr = self.multicast_group
else:
bind_addr = self.bind_addr if self.bind_addr else ''
self._sock.bind((bind_addr, self.multicast_port))
def get(self):
"""use to get the socket object to work with the select as select only accept sockets objects"""
return self._sock
def send(self, msg):
return self._sock.sendto(msg, (self.multicast_group, self.multicast_port))
def recv(self, len):
try:
response = self._sock.recvfrom(len)
return response
except socket.timeout:
return "", ""
def close(self):
self._sock.close()

how does Operating System map port number to process that use it

For a simple python server using TCP socket as below, when there comes a TCP packet, and transport layer get port number, how does OS/transport layer know which thread/process to wake up(assuming the thread/process is blocking because of recv() system call)? for the code below, both parent thread and child thread have the connectionsocket file descriptor, how OS know which one to wake up? Thanks
host = 'localhost'
port = 55567
buf = 1024
addr = (host, port)
welcomesocket = socket(AF_INET, SOCK_STREAM)
welcomesocket.bind(addr)
welcomesocket.listen(2)
while 1:
connectionsocket, clientaddr = serversocket.accept()
thread.start_new_thread(handler, (connectionsocket, clientaddr))
serversocket.close()
There is an hash map tracking all used port in the kernel space.
When a packet arrives, kernel lookup the table using the port information in the packet, find the associated socket, and notify it
Here is how linux do it http://lxr.free-electrons.com/source/net/ipv4/udp.c#L489

TCP server on MATLAB

I can't TCP from MATLAB to MATLAB
Server Code:
t = tcpip('192.168.1.14', 8000, 'NetworkRole', 'Server');
set(t, 'InputBufferSize', 900000);
fprintf('waiting for client \n');
fopen(t);
fprintf('client connected');
MATLAB waiting for client when I use fopen(t)
when I'm trying to connect from another PC on the same network I use this Code:
tc = tcpip('192.168.1.14', 8000,'NetworkRole','Client');
fopen(tc)
on the Client PC return no errors after fopen(tc) 'that's mean the Server is working fine
but on the Server PC .. It still waiting for client without detecting the Client and jump to fprintf('client connected');
when I tried both of these codes on the same PC using different versions of MATLAB it worked fine on the server and Client ..
.......
there is another problem there .. I don't need the code to be paused for waiting a client I need
there is no Client:
do something
If client exist do something else
Thank you

Python Server Client WinError 10057

I'm making a server and client in Python 3.3 using the socket module. My server code is working fine, but this client code is returning an error. Here's the code:
import socket
import sys
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('192.168.1.5', 4242)
sock.bind(server_address)
while True:
command = sock.recv(1024)
try:
os.system(command)
sock.send("yes")
except:
sock.send("no")
And here's the error:
Error in line: command = sock.recv(1024)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
What on earth is going on?
It looks like you're confused about when you actually connect to the server, so just remember that you always bind to a local port first. Therefore, this line:
server_address = ('192.168.1.5', 4242)
Should actually read:
server_address = ('', 4242)
Then, before your infinite loop, put in the following line of code:
sock.connect(('192.168.1.5', 4242))
And you should be good to go. Good luck!
EDIT: I suppose I should be more careful with the term "always." In this case, you want to bind to a local socket first.
You didn't accept any requests, and you can only recv and/or send on the accepted socket in order to communicate with client.
Does your server only need one client to be connected? If so, try this solution:
Try adding the following before the while loop
sock.listen(1) # 1 Pending connections at most
client=sock.accept() # Accept a connection request
In the while loop, you need to change all sock to client because server socket cannot
be either written or read (all it does is listening at 192.168.1.5:4242).