How can I get the port used to make a socket connection in Python 2.7? - python-2.7

I am making a IRC Client script to learn a bit about Python, that may evolve down the road... So I can connect with out issue. But I want to get the port that the socket connection is using when I use socket.connect() .
I ask, because I want to compile with the Auth RFC.
So I want to be able to send,
MYPORT, SERVPORT : USERID : Windows : Username
Is it possible to get the port of the socket being used for the out going connection? So something like this:
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect(('irc.rizon.net', 6667))
irc.send( str( irc.getsocketused() ) + ", 6667 : USERID : Windows : Username")

You can use the getsockname method on the socket, for example for IPv4;
>>> irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> irc.connect(('irc.rizon.net', 6667))
>>> addr,port = irc.getsockname()
>>> port
52675 (this will be your local port)

Related

Python 2.7 portScanner

I am wondering why my portScanner module runs and claims that all my ports are closed?
I am running Python 2.7 because thats what Violent Python(the book) uses.
Only solution I have tried so far was I have set my DNS to 8.8.8.8 and secondary to 8.8.4.4 because my socket takes 'www.google.com' as the Ip.
Code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverIp = socket.gethostbyname('www.google.com')
def pscan(port):
try:
s.connect((serverIp,port))
return True
except:
return False
for x in range(1,101):
if pscan(x):
print("Port %d is open!!!" % (x))
else:
print("Port %d is closed" % (x))
You only create a single socket and try to use it in multiple connect's. This is not possible. If you look at the details of the Exception you will notice that the first one (port 1) fails slowly because the connect timed out but the following ones all fail quickly because of "Operation already in progress".
The fix is to create a new socket before each connect. Additionally it might be helpful to reduce the time it tries to connect with s.settimeout(1).

why python does not send anything with sockets? (basic sockets)

As you can see in images below i cannot reciveve anything from client and server keeps waiting! I have tried it without firewall and no result.. :(
cmd info
Client
import socket
sock1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock1.sendto("HOLA",('192.168.0.159',25585))
sock1.close()
del sock1
Server
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('0.0.0.0',25585))
while True:
data , c = sock.recvfrom(1024);
print data
sock.close()
del sock
Your client and your server are not connected. Try this:
client:
import socket
sock1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock1.connect(('192.168.0.159',25585))
sock1.sendto("HOLA",('192.168.0.159',25585))
sock1.close()
del sock1
Your server code is good
Otherwise UDP sockets are mostly known for packets dropping

Python UDP networking socket.error: [Errno 10049]

I am trying to establish a simple UDP connection using Python code, between 2 PCs through internet.
Code run on PC_1:
import socket
import time
HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
code run on the 2nd PC:
import socket
HOST = "ip_address_of_PC1"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
While running the code on 2nd PC am getting following error message:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
change print s.recv(30) to:
data, addr = s.recvfrom(30)
print data
and in the 2nd PC code, the HOST variable needs the value of the 2nd PC ip, not the first one:
HOST = "ip_address_of_PC2"
Code run on PC1:
import socket
import time
HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
Code run on PC2:
import socket
HOST = "private ip_address_of_PC2"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)

pysftp gives pysftp.exceptions.ConnectionException: (host, port) with no details on it

I'm trying to connect to sftp server with pysftp library. Here is my code:
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection("sftp://host", "login", "password", cnopts=cnopts) as sftp:
sftp.listdir()
It gives me exception:
pysftp.exceptions.ConnectionException: ('host', port)
But I have no clue what this exception means and what the problem is.
You don't have much explanation because this library has bugs. See the source code on BitBucket.
The ConnectionException class is not well implemented:
class ConnectionException(Exception):
"""Exception raised for connection problems
Attributes:
message -- explanation of the error
"""
def __init__(self, host, port):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, host, port)
self.message = 'Could not connect to host:port. %s:%s'
As you can see, the format 'Could not connect to host:port. %s:%s' is not filled with the host and port values.
However, the name of the exception is clear: you have a connection error.
The details of the error are, unfortunately, lost:
def _start_transport(self, host, port):
'''start the transport and set the ciphers if specified.'''
try:
self._transport = paramiko.Transport((host, port))
# Set security ciphers if set
if self._cnopts.ciphers is not None:
ciphers = self._cnopts.ciphers
self._transport.get_security_options().ciphers = ciphers
except (AttributeError, socket.gaierror):
# couldn't connect
raise ConnectionException(host, port)
You can try to get the last error (not sure):
import sys
sys.exc_info()
note: I suggest you to use another library (for instance Paramiko).

Python Client is unable to receive data sent from Python Server

I am trying to send some data from my python client to python server
I have followed this link
My python client code is as follows
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '10.4.1.25';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((host , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = "16973"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
the python server code is
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
conn.close()
s.close()
The Function sendall is used to send data to client , means when I enter the text in terminal on server I should see it on client as well. But this does not happen
The output which I get is
Server Output
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656
Client Output
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I am unable to know what's going wrong here?
Also how can I send data (message) from Python Client to Python server??
Any help would be great !
Thanks!