与urllib2连接后如何确定服务器的IP地址? [英] How to determine the IP address of the server after connecting with urllib2?

查看:78
本文介绍了与urllib2连接后如何确定服务器的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用urllib2从服务器下载数据.但是我需要确定所连接服务器的IP地址.

I am downloading data from a server using urllib2. But I need to determine the IP address of the server to which I am connected.

import urllib2
STD_HEADERS = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,
                    */*;q=0.8',
                'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
                'Accept-Language': 'en-us,en;q=0.5',
                'User-Agent': 'Mozilla/5.0 (X11; U; Linux x86_64;en-US;rv:1.9.2.12)     
                           Gecko/20101028 Firefox/3.6.12'}
request = urllib2.Request(url, None, STD_HEADERS)
data =  urllib2.urlopen(request)

请不要要求我使用URL查找IP地址,因为这不能保证从中下载数据的服务器和IP地址查询在使用"HTTPRedirects"或"HTTPRedirects"的情况下都解析为相同的IP地址.负载均衡服务器

Please don't ask me to find the IP address using the URL as this does not guarantee that the server from which the data is downloaded and the IP address query resolve to the same IP address in case of 'HTTPRedirects' or a loadbalancing server

推荐答案

import urllib2, socket, urlparse

# set up your request as before, then:
data = urllib2.urlopen(request)
addr = socket.gethostbyname(urlparse.urlparse(data.geturl()).hostname)

data.geturl()在进行任何重定向后,返回用于实际检索资源的URL.然后用urlparse提取主机名,并将其移交给socket.gethostbyname以获得IP地址.

data.geturl() returns the URL that was used to actually retrieve the resource, after any redirects. The hostname is then fished out with urlparse and handed off to socket.gethostbyname to get the IP address.

对于给定的主机名,某些主机可能具有多个IP地址,因此,仍然有可能由其他服务器来完成该请求,但这与您将要达到的距离很近. URL请求之后的gethostbyname仍将使用您的DNS缓存,除非您要处理的生存时间(例如1秒),否则您将获得与刚才使用的服务器相同的服务器

Some hosts may have more than one IP address for a given hostname, so it's still possible that the request was fulfilled by a different server, but this is as close as you're gonna get. A gethostbyname right after the URL request is going to use your DNS cache anyway and unless you're dealing with a time-to-live of, like, 1 second, you're going to be getting the same server you just used.

如果这还不够,您可以断开线程并在仍连接到远程服务器的同时执行lsof.我确定您可以说服urllib2暂时保持连接打开状态,这样可以成功.但是,这似乎比它值得的工作还要多.

If this is insufficient, you could spin off a thread and do a lsof while still connected to the remote server. I'm sure you could convince urllib2 to leave the connection open for a while so this would succeed. This seems like rather more work than it's worth, though.

这篇关于与urllib2连接后如何确定服务器的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆