本文整理汇总了Python中stun.get_ip_info函数的典型用法代码示例。如果您正苦于以下问题:Python get_ip_info函数的具体用法?Python get_ip_info怎么用?Python get_ip_info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_ip_info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_nat_type
def get_nat_type():
parser = optparse.OptionParser(version=stun.__version__)
parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
default=False, help="Enable debug logging")
parser.add_option("-H", "--host", dest="stun_host", default=None,
help="STUN host to use")
parser.add_option("-P", "--host-port", dest="stun_port", type="int",
default=3478, help="STUN host port to use (default: "
"3478)")
parser.add_option("-i", "--interface", dest="source_ip", default="0.0.0.0",
help="network interface for client (default: 0.0.0.0)")
parser.add_option("-p", "--port", dest="source_port", type="int",
default=54320, help="port to listen on for client "
"(default: 54320)")
(options, args) = parser.parse_args()
if options.DEBUG:
stun.enable_logging()
kwargs = dict(source_ip=options.source_ip,
source_port=int(options.source_port),
stun_host=options.stun_host,
stun_port=options.stun_port)
nat_type, external_ip, external_port = stun.get_ip_info(**kwargs)
print "NAT Type:", nat_type
print "External IP:", external_ip
print "External Port:", external_port
return nat_type, external_ip, external_port
示例2: get_NAT_status
def get_NAT_status(stun_host=None):
"""
Given a server hostname, initiate a STUN request to it;
and return the response in the form of a dict.
"""
response = stun.get_ip_info(stun_host=stun_host, source_port=0)
return {'nat_type': response[0],
'external_ip': response[1],
'external_port': response[2]}
示例3: start_node
def start_node(self, port):
self.dynamic_ip = stun.get_ip_info()[1]
try:
self.loadState(OBNodeStrings.knode_pickle)
except IOError:
print "knode.p does not exist, network has not been saved."
print "%s:\t%s" % (self.dynamic_ip, self.node.port,)
示例4: test_stun
def test_stun():
"""Get external IP address from stun, and test the connection capabilities"""
log.info("STUN - Testing connection...")
src_port=randint(1025, 65535)
stun = get_ip_info(source_port=src_port)
log.debug(stun)
port_mapping = PRESERVES_PORT if stun[2] == src_port else None
seq_stun = None
if port_mapping != PRESERVES_PORT:
"""Test for sequential port mapping"""
seq_stun = get_ip_info(source_port=src_port+1)
log.debug(seq_stun)
port_mapping = SQUENTIAL_PORT if stun[2] + 1 == seq_stun[2] else RANDOM_PORT
log.debug("STUN - Port allocation: "+port_strings[port_mapping])
seq_stun = seq_stun or None
ret = (stun, seq_stun), port_mapping, src_port
return ret
示例5: run
def run(self):
self._log("Getting external IP info")
nat_type, external_ip, external_port = stun.get_ip_info()
#nat_type, external_ip, external_port = None, "0.0.0.0", 12345
self._log("Public addr: %s:%s" % (external_ip, external_port))
self._log("Connecting to DHT")
self.dht = DHT("0.0.0.0", 52525)
self.public_contact = (external_ip, external_port)
for peer in self.core.config.get("peers", self._default_peers):
self.dht.bootstrap(peer["host"], peer["port"])
示例6: lback_default_focused_agent
def lback_default_focused_agent():
ip_info =stun.get_ip_info()
public_ip = ip_info[1]
local_ip = "127.0.0.1"
## prefer local
agents = lback_agents()
for agent in agents:
if local_ip==agent.host:
return agent.id
if public_ip==agent.host:
return agent.id
raise Exception("No default focused agent available")
示例7: update_loop
def update_loop(prefs, client):
while True:
nat_type, ip, port = get_ip_info()
for domain in prefs.get('domains'):
result = client.update_dns_record(domain['dns'], ip)
if result:
logger.info("Updated DNS Record")
else:
logger.info("DNS is already set.")
logger.info("Sleeping for %s seconds" % prefs.get('interval'))
sleep(prefs.get('interval'))
pass
示例8: connect_to_server
def connect_to_server(self):
ch = raw_input("Choose how to setup a connection\n 1.m for private server\n 2.p for public server\n")
self.local_port = int(raw_input("enter port to listen: "))
if ch == 'p':
self.nat_type, self.my_ip, self.port = stun.get_ip_info('0.0.0.0', self.local_port)
if not self.my_ip:
log.warn('Stun request failed! switching to manual server')
else:
log.info('External address: %s:%s' % (self.my_ip, self.port))
self.listen_address = ('0.0.0.0', self.local_port)
log.info('Listening on address: %s:%s' % (self.listen_address[0], self.listen_address[1]))
self.linsocket.bind(self.listen_address)
示例9: connectionSupport
def connectionSupport(self):
"""
This method provide reserve of external port on external router
or rewrite info about external port on Signal server.
"""
self.transport.write('[True, "something"]', ('10.0.16.24', 4444))
time.sleep(2)
if self.s_connect:
self.s_connect = False
self.connectionSupport()
else:
self.sendDatagram('[False, "Client 911", %s]' % str(stun.get_ip_info()[1:]))
self.connectionSupport()
示例10: uiStunserver
def uiStunserver():
global PeerAddr
global PeerIp
global port
nat_type, Myip, port = stun.get_ip_info()
if Myip=="" or Myip=="none":
print "Stun request falied! switching to manual server"
uiMyserver()
else:
listenport=port
listenAddr=('0.0.0.0',listenport)
listensoc.bind(listenAddr)
print "your ip is: '"+Myip+ "' and your port is: '"+str(port)+"'"
示例11: ReceiverTask
def ReceiverTask(addr, port, bootstrap=None):
global t_recv_buffer
receiver = Receiver((addr, port))
addr, port = receiver.get_addr()
cache["addr"], cache["port"] = addr, port
port_map = [(port, "UDP"), (port + 1, "UDP")]
external_ip, lan_addr = do_UPNP_mapping(port_map)
#external_ip, lan_addr = "161.53.120.206", get_lan_addr()
if external_ip:
logging.info("[+] uPnP maps:{0}:{1} -> {2}:{3}".format(
lan_addr, port, external_ip, port))
cache["addr"], cache["port"] = lan_addr, port
#cache["addr"], cache["port"] = external_ip, port
else:
# Do STUN probe
logging.info("[-] external_ip unknown: sending STUN probe...")
import stun
nat_type, external_ip, external_port = stun.get_ip_info()
logging.info("[+] STUN probe: {0}:{1}, {2}".format(
external_ip, external_port, nat_type))
#cache["addr"], cache["port"] = external_ip, port #, external_port
# TODO: if nat_type == symmetric -> import turn
logging.info("cache['addr'] = {0}, cache['port'] = {1}".format(
cache["addr"], cache["port"]))
p = Process(target=tftp_server, args=(port + 1, "./tasks/"))
p.start()
if bootstrap:
yield NewTask(Bootstrap(bootstrap))
while True:
logging.info("Waiting for packets in ReceiverTask")
resp, addr, rpc_no, uuid = yield receiver.recv()
packet = {"resp": resp,
"addr": addr,
"rpc_no": rpc_no,
"uuid": uuid }
#logging.debug("Packet received {}".format(packet))
if not socket_observable.notify_one(packet):
logging.debug("Not observer for notify, sending response...")
sender = Sender(packet["addr"],
(cache["addr"], cache["port"]),
cache["uuid"])
yield sender.send_resp(packet["resp"], packet["rpc_no"])
示例12: main
def main():
try:
parser = make_argument_parser()
args = parser.parse_args()
if args.mode == CLIENT:
nat_type, host, port = stun.get_ip_info()
reactor.listenUDP(0, Client(host, port, args.message))
reactor.run()
elif args.mode == SERVER:
reactor.listenUDP(0, Server())
reactor.run()
else:
parser.print_help()
except KeyboardInterrupt:
sys.exit()
示例13: setup_external_ip
def setup_external_ip(self, hostname=None):
"""
Detects and change hostname if needed (not fully implemented so far)
:param hostname:the current hostname of the robot
"""
nat_type, current_external_ip, external_port = stun.get_ip_info()
log.info("Nat type %s, external IP %s, external port %s", nat_type, current_external_ip, external_port)
dns_registered_ip = dns.resolver.query(hostname)[0]
if str(current_external_ip) != str(dns_registered_ip):
log.info(
"DNS need change. Currently on DNS '%s', current external IP '%s'",
dns_registered_ip,
current_external_ip,
)
else:
log.info("DNS and current external IP ('%s') are the same, no DNS change needed", current_external_ip)
示例14: main
def main():
try:
options = make_argument_parser().parse_args()
if options.debug:
logging.basicConfig()
stun.log.setLevel(logging.DEBUG)
nat_type, external_ip, external_port = stun.get_ip_info(
source_ip=options.source_ip,
source_port=options.source_port,
stun_host=options.stun_host,
stun_port=options.stun_port
)
print('NAT Type:', nat_type)
print('External IP:', external_ip)
print('External Port:', external_port)
except KeyboardInterrupt:
sys.exit()
示例15: main
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(10)
nat_type, external_ip, external_port = stun.get_ip_info()
other_client, other_client_nat = request_conn(s, addr2str((external_ip, external_port)))
connected = None
s.settimeout(2)
while True:
# discover procedure
while not connected:
for addr in [other_client, other_client_nat]:
print("Try to conn to addr: {}".format(addr))
s.sendto("discover", addr)
try:
data, addr = s.recvfrom(1024)
s.sendto("discover", addr)
except socket.timeout:
continue
connected = addr
print("Connected to: {}".format(addr))
s.sendto("hello i'm here", connected)
data, addr = s.recvfrom(1024)
print("Received from {}: {}".format(addr, data))
time.sleep(1)