0

my server copy it if you want! :) how do i find my ipv4 using python? can i you try to keep it real short?

import socket

def Main():
    host = '127.0.0.1'
    port = 5000

    s = socket.socket()
    s.bind((host,port))

    s.listen(1)
    c1, addr1 = s.accept()
    sending = "Connection:" + str(addr1)
    connection = (sending) 
    print(connection)
    s.listen(1)
    c2, addr2 = s.accept()
    sending = "Connection:" + str(addr2)
    connection = (sending)
    print(connection)
    while True:
        data1 = c1.recv(1024).decode('utf-8')
        data2 = c2.recv(1024).decode('utf-8')
        if not data1:                            
            break
        if not data2:
            break
        if data2:
            c1.send(data2.encode('utf-8'))
        if data1:
            c2.send(data1.encode('utf-8'))
    s.close() 

if __name__== '__main__':
    Main() 

thx for the help i appreciate it!

MaxLunar
  • 653
  • 6
  • 24
Matt
  • 13
  • 3

1 Answers1

0

That's all you need for the local address (returns a string):

socket.gethostbyname(socket.gethostname())
Uriel
  • 15,579
  • 6
  • 25
  • 46
  • thx! for the help! – Matt Oct 19 '16 at 15:59
  • @MatthewYeomans-Jones> you may want to consider that _“The gethostbyname*(), functions are obsolete. Applications should use getaddrinfo(3) instead”_ (from the man page). – spectras Oct 19 '16 at 15:59
  • By the way, on my laptop, this returns `127.0.1.1` – spectras Oct 19 '16 at 16:04
  • @spectras see this: https://serverfault.com/questions/363095/why-does-my-hostname-appear-with-the-address-127-0-1-1-rather-than-127-0-0-1-in – Dartmouth Oct 19 '16 at 16:05
  • @Dartmouth> Thanks, I knew the reason actually, I was just pointing out that this solution is unreliable, as it gives a wrong result with default install of several distribs. – spectras Oct 19 '16 at 16:07