Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect two computers on the same network using python

This is the server side program

import socket

s = socket.socket()
host = socket.gethostname()
port = 9077
s.bind((host,port))
s.listen(5)

while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))
    c.send("Thank you for connecting")
    c.close()

This is the client program

import socket

s = socket.socket()
host = socket.gethostname()
port = 9077
s.connect((host, port))
print s.recv(1024)

When i run these two programs on the same computer, it works perfectly. But when i run the client and server programs in two different computers on the same network, the program doesn't work.

Can anyone please tell me how to send message from one computer to another on the same network.

This is the first time i'm doing any network programming. Any help would be appreciated

Thanks in advance

like image 462
shashank93rao Avatar asked Jun 28 '13 02:06

shashank93rao


People also ask

How do I connect two computers as client and server?

Connect all of the computers to be networked to a router. Attach one end of an Ethernet cable to a computer's network card and the other end to the proper connection on the router. Do this for each computer and the server to be networked. Power on the router and all of the computers.

What is network connectivity in python?

Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.


1 Answers

You are connecting from the client to the client's computer, or well attempting to, because you are using the client's hostname rather than the servers hostname/ip address.

So, to fix this change the line s.connect((host, port)) so that the host points to the servers ip address instead of the client's hostname.

You can find this by looking at your network settings on the server and doing the following:

host = "the ip found from the server's network settings"
like image 161
sean Avatar answered Oct 20 '22 00:10

sean