Search code examples
pythonpython-3.xsocketsmessaging

im having problems in setting ip address in python socket library


so i want to make a Messenger and i create it with the socket library. by creating a server side and a client side. where two need to be on same internet ( i think so ! ) here is my code:

server side:

import socket
import os
os.system('clear')
s = socket.socket()
ip = 'localhost'
port = 9999
s.bind((ip,port))
s.listen()
print ('please wait...')
c , addr =s.accept()
print ('someone has joined!')

class color : 
    GREEN = '\033[92m'
    RED = '\033[91m'
    WHITE = '\033[0m'

while True :
    msg = input(color.RED + 'your message: ' )
    c.send(msg.encode('utf8'))
    print (color.GREEN + c.recv(1024).decode())

client side :

import socket
import os
os.system('clear')
s=socket.socket()
ip='192.168.1.3'
port=9999
s.connect((ip,port))
print('you have been connected' )
class color :
    GREEN = '\033[92m'
    RED = '\033[91m'
    WHITE = '\033[0m'

while True:
    print (color.RED + s.recv(1024).decode())
    msg = input(color.GREEN + 'your message : ')
    s.send(msg.encode('utf8'))

here , i need to set an ip address for each side. i tried all methods but nothing worked. do you have a recommendation to how to do it ? thanks.

errors on each method :

method 1 : setting server side ip 'local_host' or any other gethostname or gethostbyname : server side works fine but client side does not connect

method 2 : setting server ip address to something like '192.168.0.3' : server side makes an error : OSError : [WinError 10049] The requested address is not valid in its context

edit on main : the methods you guys recommended give an error on client side :

connectionrefusederror: [WinError 10061] no connection could be made 
because the target machine refused it

Solution

  • I don’t know if this is correct, but it seems from most of the examples that people use ip = socket.gethostbyname(socket.gethostname()), which lines up with what I know about sockets in C. So try replacing ip = “localhost” with ip = socket.gethostbyname(socket.gethostname()).

    As the President recommended, you could also bind to the ip “0.0.0.0” during debugging as it will listen on all interfaces, although this will probably not be an issue.