Binvention
Binvention

Reputation: 1077

Python socket listening to specific interface

I currently have a raspberry pi that is set up as a wifi to ethernet bridge. The raspberry pi acts as an access point to the entire ethernet subnet that I have. The subnet and the network bridge work perfectly but when I try to get my python program on the raspberry pi to listen to requests on the ethernet interface/subnet it doesn't seem to do that. It is set to bind the socket to ('',10000) but it never receives any messages. However, it is able to send messages via sockets to the subnet just fine, just not receive. I think it is listening to the wifi interface rather than the ethernet one but I'm not sure how to specify which interface the socket is suppose to listen to.

here is my receiving code

receive_group = ('',10000)
receive = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

receive.bind(receive_group)

while(True):
   data, address = receive.recv(65536)
   print(data)

Upvotes: 0

Views: 2707

Answers (3)

Binvention
Binvention

Reputation: 1077

Turns out it wasn't anything with python. When I created the access point on the pi it created a firewall rule that blocked that port even though I never configured the firewall that way. Adding an exception to that port fixed my problem

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149175

The bind part should be correct. The receive part is wrong because recv only return the (bytes) data, you should use recvfrom to also get the sender address. But this should work:

import socket
receive = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receive.bind(('', 10000))
while True:
    data, address = receive.recvfrom(64)
    print(data, address)

I used this code for the send part:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b'foo', (addr, 10000))

where addr is one of the (reachable) addresses of the receiver, and the receiver could successfully receive data from any of its interfaces.

Upvotes: 1

rozumir
rozumir

Reputation: 905

To get something from socket.recv something must connect to this socket and send something. Are you sure that some program on the network is doing this?

For listening/sniffing to packets and network traffic, better use pyshark.

Upvotes: 0

Related Questions