0

I have the below code and it receives the data I want, how I want, then terminates. How can I set this to connect to my client that always has the same IP and remain connected or listening from that client?

Its a barcode scanner and sends the data fine i just need to be always listing for it.

Servercode.py

import socket   #for sockets
import sys  #for exit

try:
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM,)
except socket.error as err_msg:
  print ('Unable to instantiate socket. Error code: ' + str(err_msg[0]) + ' , Error message : ' + err_msg[1])
sys.exit();

print ('Socket Initialized')

host = socket.gethostname() 
port = 12345                
s.bind((host, port))        

s.listen(5)                 
print ('listening....')


conn, addr = s.accept()
print ('Got connection from', addr)
while 1:
 data = conn.recv(1024)
 stringdata = data.decode('ascii')
 if not data: break
 print ('received data:', stringdata)
conn.close()
DevJustin
  • 103
  • 1
  • 7
  • It looks like your client is disconnecting. Are you asking how to stop the client from disconnecting? – John Zwinck Aug 26 '17 at 00:21
  • That would be great, but more looking for the most secure approach connecting ONLY to the client with the IP of 192.168.1.200. So as long as the server is running it will always be listening ready to accept in the background. – DevJustin Aug 26 '17 at 00:46
  • Oh, so your question is how to refuse connections from clients with IP addresses other than a specific one? – John Zwinck Aug 26 '17 at 01:24
  • YES exactly that :) – DevJustin Aug 26 '17 at 01:28

1 Answers1

0

You want to reject connections from IP addresses other than a specific one. You already have most of what you need:

print ('Got connection from', addr)

Just add something like this:

if addr[0] != '192.168.1.200':
    conn.close()
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thank you! I knew it was something along those lines. I made it even more secure by just doing `s.close()` – DevJustin Aug 26 '17 at 03:40