Reputation: 8098
I am trying out an example from the book Foundations of python network programming, which lists a simple UDP client/server program. The first program had the client/server within the same machine, but the second one has the server listening for any machines. The book does not detail on how to establish a connection between two machines.
I have two computers which are both connected to the internet. How can I configure them to send and receive packets from each other.
Here is the source code from the example:
#!/urs/bin/env python
# UDP client and server for talking over a network
import random, socket, sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if 2<= len(sys.argv) <= 3 and sys.argv[1] == 'server':
interface = sys.argv[2] if len(sys.argv)>2 else ''
s.bind((interface,PORT))
print 'Listening at ', s.getsockname()
while True:
data, address = s.recvfrom(MAX)
if random.randint(0,1):
print 'The client at ', address, 'says:', repr(data)
s.sendto('Your data was %d bytes ' % len(data) ,address)
else:
print 'Pretending to drop packet from ', address
elif len(sys.argv)==3 and sys.argv[1] == 'client':
hostname = sys.argv[2]
s.connect((hostname,PORT))
print 'Client socket name is', s.getsockname()
delay = 0.1
while True:
s.send('This is another message')
print 'Waiting up to', delay, 'seconds for a reply'
s.settimeout(delay)
try:
data = s.recv(MAX)
except socket.timeout:
delay *= 2 # wait even longer for the next request
if delay > 2.0:
raise RuntimeError('I think the server is down')
except:
raise # a real error so we let the user see it
else:
break
print 'The server says ', repr(data)
I found out the public IP of the computer running as server, and tried to connect to it from another machine running as client, but I didn't get response. I am not behind a proxy in either computers.
Upvotes: 4
Views: 13873
Reputation: 54
Assume your code file named cs.py , server interface address 192.168.1.2 and server external address (internet address) 2.2.2.2
On the server run
cs.py server 192.168.1.2
Make sure your server side router between LAN and WAN have NAT for server
On the client side run
cs.py client 2.2.2.2
Upvotes: 1
Reputation: 20576
To start, if you really want to try such application and learn, you would need to have these two machine connected on a local network within same subnet so each machine have address like 192.168.x.2 and 192.168.x.2, this way you will know what is happening...
Then when you run above application in one machine run as "_application_name server" and on other machine run as "_application_name client". You will see both machine are connected and start communicating within your local network.
On Internet, it would be hard to get your IP/PORT working due to lots of secure channels and pretty much you will not get what you want.
Upvotes: 1