Python socket.getpeername() Examples

The following are 10 code examples of socket.getpeername(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: socks.py    From torba with MIT License 6 votes vote down vote up
def _connect_one(self, host, port):
        """Connect to the proxy and perform a handshake requesting a
        connection to (host, port).

        Return the open socket on success, or the exception on failure.
        """
        client = self.protocol(host, port, self.auth)
        sock = socket.socket()
        loop = asyncio.get_event_loop()
        try:
            # A non-blocking socket is required by loop socket methods
            sock.setblocking(False)
            await loop.sock_connect(sock, self.address)
            await self._handshake(client, sock, loop)
            self.peername = sock.getpeername()
            return sock
        except Exception as e:
            # Don't close - see https://github.com/kyuupichan/aiorpcX/issues/8
            if sys.platform.startswith('linux') or sys.platform == "darwin":
                sock.close()
            return e 
Example #2
Source File: socks.py    From lbry-sdk with MIT License 6 votes vote down vote up
def _connect_one(self, host, port):
        """Connect to the proxy and perform a handshake requesting a
        connection to (host, port).

        Return the open socket on success, or the exception on failure.
        """
        client = self.protocol(host, port, self.auth)
        sock = socket.socket()
        loop = asyncio.get_event_loop()
        try:
            # A non-blocking socket is required by loop socket methods
            sock.setblocking(False)
            await loop.sock_connect(sock, self.address)
            await self._handshake(client, sock, loop)
            self.peername = sock.getpeername()
            return sock
        except Exception as e:
            # Don't close - see https://github.com/kyuupichan/aiorpcX/issues/8
            if sys.platform.startswith('linux') or sys.platform == "darwin":
                sock.close()
            return e 
Example #3
Source File: socks.py    From torba with MIT License 5 votes vote down vote up
def __init__(self, address, protocol, auth):
        """A SOCKS proxy at an address following a SOCKS protocol.  auth is an
        authentication method to use when connecting, or None.

        address is a (host, port) pair; for IPv6 it can instead be a
        (host, port, flowinfo, scopeid) 4-tuple.
        """
        self.address = address
        self.protocol = protocol
        self.auth = auth
        # Set on each successful connection via the proxy to the
        # result of socket.getpeername()
        self.peername = None 
Example #4
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def get_client_addr(self):
        return super(IndexHandler, self).get_client_addr() or self.request.\
                connection.stream.socket.getpeername() 
Example #5
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def get_client_addr(self):
        return super(WsockHandler, self).get_client_addr() or self.stream.\
                socket.getpeername() 
Example #6
Source File: server.py    From FlowState with GNU General Public License v3.0 5 votes vote down vote up
def sendAck(socket):
    #print("sending ack to "+str(socket.getpeername()))
    ack = FSNObjects.ServerEvent(FSNObjects.ServerEvent.ACK)
    send(ack,socket) 
Example #7
Source File: server.py    From FlowState with GNU General Public License v3.0 5 votes vote down vote up
def send(message, socket):
    #print("send()")
    #global outboundMessages

    #outboundMessages.append({"data":message,"socket":socket})
    try:
        dataOut = str(message).encode("utf-8")+delim
        #print("sending message to client: "+str(socket.getpeername()[0])+": "+str(dataOut))
        socket.send(dataOut)
    except Exception as e:
        print(traceback.format_exc())
        socket.close()
        # if the link is broken, we remove the client
        #remove(socket) 
Example #8
Source File: socks.py    From lbry-sdk with MIT License 5 votes vote down vote up
def __init__(self, address, protocol, auth):
        """A SOCKS proxy at an address following a SOCKS protocol.  auth is an
        authentication method to use when connecting, or None.

        address is a (host, port) pair; for IPv6 it can instead be a
        (host, port, flowinfo, scopeid) 4-tuple.
        """
        self.address = address
        self.protocol = protocol
        self.auth = auth
        # Set on each successful connection via the proxy to the
        # result of socket.getpeername()
        self.peername = None 
Example #9
Source File: client.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectionSuccess(self):
        socket = self.sub.socket
        self.sub.state = "dead"
        del self.sub
        self.state = "connected"
        self.cancelTimeout()
        p = self.factory.buildProtocol(self.buildAddress(socket.getpeername()))
        self.transport = self.transport_class(socket, p, self)
        p.makeConnection(self.transport) 
Example #10
Source File: tcp_http_https.py    From honeypot with GNU General Public License v2.0 4 votes vote down vote up
def handle_tcp_http(socket, dstport):
	socket = TextChannel(socket)

	try:
		keep_alive = True
		while keep_alive:
			firstline = readline(socket).strip()
			rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline)

			if not rematch:
				raise Exception('Unexpected request')

			verb = rematch.group(1)
			url = rematch.group(2)

			# Skip headers
			keep_alive = False
			user_agent = ''
			while True:
				header = readline(socket).strip()
				if header == '':
					break
				elif header.upper() == 'CONNECTION: KEEP-ALIVE':
					keep_alive = True
				elif header.upper().startswith('USER-AGENT: '):
					user_agent = header[len('USER-AGENT: '):]

			session_token = uuid.uuid4().hex
			log_append('tcp_http_requests', socket.getpeername()[0], dstport, verb, url, user_agent, session_token)

			socket.send("HTTP/1.0 200 OK\nServer: microhttpd (MontaVista/2.4, i386-uClibc)\nSet-Cookie: sessionToken={}; Expires={}\nContent-Type: text/html\nContent-Length: 38\nConnection: {}\n\nmicrohttpd on Linux 2.4, it works!\n\n".format(session_token, __getexpdate(5 * 365 * 24 * 60 * 60), "keep-alive" if keep_alive else "close"))
	except ssl.SSLError as err:
		print("SSL error: {}".format(err.reason))
		pass
	except Exception as err:
		#print(traceback.format_exc())
		pass

	try:
		print("-- HTTP TRANSPORT CLOSED --")
		socket.close()
	except:
		pass