I have a socket that I connect by it to a web page and get something.

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('example.ir', 80))
mysock.send('GET http://example.ir/index.php HTTP/1.0\n\n')
while True:
    print"##########################"
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print data

mysock.close()

Now, I like to know, what is the port and IP of mysock?
What IP and port mysocket use to connect to example.ir?

有帮助吗?

解决方案

To get the IP and port of mysock just do:

ip, port = mysock.getsockname()

Likewise, to get the same information about the peer it is connected to do:

ip, port = mysock.getpeername()  # 'example.ir', 80
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top