使用套接字从addr中提取IP

时间:2017-01-11 13:16:10

标签: python-2.7 sockets

我正在使用python套接字侦听特定端口并接受连接,我希望能够看到连接IP但是有一种标准的连接输出格式。

('127.0.0.1', 34447)

如何从此字符串中仅提取IP?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('',23))
s.listen(10)
def tel_con():
    while 1:
        try:
            conn, addr = s.accept()
            printInfo(addr)
        except KeyboardInterrupt:
            s.close()
            sys.exit()

1 个答案:

答案 0 :(得分:0)

正如nos所指出的,解决方案是addr [0]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('',23))
s.listen(10)
def tel_con():
    while 1:
        try:
            conn, addr = s.accept()
            printInfo(addr[0])
        except KeyboardInterrupt:
            s.close()
            sys.exit()