Creating a TCP/IP connection on already-networked computers

John Salerno johnjsal at gmailNOSPAM.com
Sat Jun 14 20:47:21 CEST 2008


John Salerno wrote:
> if the program I write actually works and allows the two 
> computers to speak to each other, will that be a result purely of the 
> program, or will it have anything to do with the fact that they are 
> already on a home network together?

Here are the two programs. Server first, then client. They work, which 
in itself amazes me that it's so simple to create a network connection 
like this! But my basic question is this: would this connection work if 
the two computers (each running one of these scripts) were completely 
unrelated to one another? My two are on a home network, but if I were to 
run the server program and have a friend of mine (who lives somewhere 
else) run the client program, would it still work?

-----
#!/usr/bin/env python

from socket import *
from time import ctime

HOST = '192.168.1.100'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
     print 'waiting for connection...'
     tcpCliSock, addr = tcpSerSock.accept()
     print '...connected from:', addr

     while True:
         data = tcpCliSock.recv(BUFSIZ)
         if not data:
             break
         tcpCliSock.send('[%s] %s' % (ctime(), data))

     tcpCliSock.close()

tcpSerSock.close()
-----

-----
#!/usr/bin/env python

from socket import *

HOST = '192.168.1.100'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
     data = raw_input('> ')
     if not data:
         break
     tcpCliSock.send(data)
     data = tcpCliSock.recv(BUFSIZ)
     if not data:
         break
     print data

tcpCliSock.close()
-----



More information about the Python-list mailing list