Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Connect via LAN?

Just a preface to this question: I have no clue what I am doing, so please excuse any stupidity.

I am making a socket based chatroom that I want to use on a local network (My dad's computer and mine connected through the same wifi).

Here is the server code:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(1)
while True:
    # Find connections
    connection, client_address = sock.accept()
    try:
        data = connection.recv(999)
        print data

    except:
        connection.close()

Here is the client:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address

while True:
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(server_address)
        message=raw_input('Message: ')
        if message=='quit':
            break
        sock.sendall(message)
    except:
        break
sock.close()

When I run the client on one computer, and the server on the other.. the connection isn't made. I believe it is because of server_address = ('localhost', 10000) but I am not sure.. any suggestions?

like image 663
Sam Tubb Avatar asked Jan 12 '23 15:01

Sam Tubb


1 Answers

You have to use your local ip's for example if you are going to be the server you have to use your own ip in the server code:

to find the ip:

ipconfig - Windows CMD
ifconfig - Linux Shell, Mac Terminal

after you know your ip you have to replace localhost with your own ip:

Server code:

server_address = ('myip', 10000)

so in your father's computer you have to connect to your server:

Client Code:

server_address = ('myip', 10000)
like image 74
Victor Castillo Torres Avatar answered Jan 21 '23 12:01

Victor Castillo Torres