1

I'm trying to create the ability for a client to enter the IP address/port of a server and connect to it. In order to do this, I need the server's public IP address/port. Is there a good way to do this? What I've tried so far is...

ip_address = urllib.request.urlopen(<my web server>).read()

with the web server just containing the php script:

<?php echo $_SERVER["REMOTE_ADDR"]?>

And just storing the port from the

s.bind(('', port))

Connecting to this ip address and port times out. Is there a better way to do this?

EDIT: OK so basically I'm trying to establish a connection over the internet, without knowing exactly what my router is going to be doing. I can use a webserver with any code if necessary, as I have access to permanent webspace. This is what I have right now.

Server:

import urllib.request
import threading
import socket

socket_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('', 0))

s.listen(10)


def listener(socket):
    while(1):
        data = socket.recv(1024)
        print (data)

def accepter():
    while(1):
        socket, addr = s.accept()
        socket_list.append(socket)
        threading.Thread(target = listener, args = (socket,)).start()

ip_address = (urllib.request.urlopen("<MY WEB SERVER HERE>").read()).decode('utf-8')
print (ip_address)
print (s.getsockname()[1])

threading.Thread(target = accepter, args = ()).start()

Client:

import socket

print ("Enter IP Address")
ip_address = input()
print ("Enter Port")
port = int(input())

s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((ip_address, port))s2.send("Connected!")
s2.close()

When I run the client I'm entering the IP address and port that are outputted by the server. Needless to say, this doesn't work.

SwiftCore
  • 659
  • 9
  • 17

1 Answers1

1

I thought this was a good question you can do it like this if you didn't want to have your server set up like you have:

""" Easy IP Getter """
import json
import urllib2

info = json.loads(urllib2.urlopen("http://jsonip.com").read())
ip = info["ip"]
print ip

It depends on an outside service however which isn't the best, if they stop working you stop working.

Noelkd
  • 7,686
  • 2
  • 29
  • 43
  • I guess I should also say that I need the port number? Should I try and set up a connection through a webserver to determine the port? I have webspace I can use. – SwiftCore Feb 24 '14 at 21:26