how to receive data from telnet connection in python - python

I want to create program that if some one connects to my pc at port 43 and sends some data for example website name
then I perform some function on that website name and return final value
but this program is not function
#!/usr/bin/env python
import sys
import socket
import urllib2
s = socket.socket() # Create a socket object
host = '192.168.0.140' # Get local machine name
BUFFER_SIZE = 1000000000
port = 43 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = c.recv(BUFFER_SIZE)
print data
x = urllib2.urlopen('http://192.168.0.65:2020/?websitename='+data ).read()
print x
c.send(x)
c.close() # Close the connection
Also other problem is while testing if I close this script by hitting ctrl + c then it exits with traceback, but main problem is if next time I run this script then it shows following error
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
so I have to change port everytime I start script which is really painful
Any suggestions will be helpful, thank you

Don't use ports below 1000, if you are not sure that you need them. Why, you can read here http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
Speaking about telnet what you mean? Network protocol http://en.wikipedia.org/wiki/Telnet ? Or something else?

Related

Communication between 2 python script in which the first one is continuously running

I have 2 python scripts.
To make it simple
1st script :
It is a simple infinite while loop in which a variable 'x' is being increased by 1(This script is always running)
Now what I want a 2nd script, when I call this script it should give me the present value of x
I read about multiprocessing ,pipe and queue but was not able to implement it
EDIT:
I tried the socket solution and I am getting errors
Client Side
import serial
import time
from multiprocessing import Process
import sys
import socket
s=socket.socket()
port=43470
s.connect(('127.0.0.1',port))
sertx = serial.Serial('COM4', 115200)
while 1:
for i in range(4):
msg = str(i+1)
# print('sending: ',msg.encode())
msgstat = 'A' + msg
#print(msgstat)
#print(type(msgstat))
tx_t = time.time()
sertx.write(msg.encode())
tx_t=str(tx_t)
s.send(tx_t.encode())
s.close()
time.sleep(0.001)
Error - File ".\tx.py", line 23, in
s.send(tx_t.encode())
OSError: [WinError 10038] An operation was attempted on something that is not a socket
PS C:\Users\ambuj\Documents\Python Scripts>
Server
import socket
s = socket.socket()
port = 43470 # make this any random port
s.bind(('127.0.0.1', port))
s.listen(5) # put the socket into listen mode
while True:
c, addr = s.accept()
data = c.recv(1024).decode("utf-8") # This data is received from the client script
print(data)
c.close()
You can surely achieve this thing using socket communication. Just create a server script like this which will listen to any incoming data to a specific port...
import socket
s = socket.socket()
port = 43470 # make this any random port
s.bind(('127.0.0.1', port))
s.listen(5) # put the socket into listen mode
while True:
c, addr = s.accept()
data = c.recv(1024).decode("utf-8") # This data is received from the client script
c.close()
Now in your client script, you have to connect to the socket that is binded in that port. Make a client script like this...
import socket
s = socket.socket()
port = 43470 # Use the same port number here as you did in the server script.
s.connect(('127.0.0.1', port))
s.send(b"This data will be received by the server!")
s.close()
You can do the reverse as well. So the server will be able to send the data to the client script. Its a two-way communication.
Remeber: This is just a simple demonstraction to make things work. In actual case, modification is much needed.

Python 2.7 Socket programming ports

I had an exercise of port carousel which means that I need to build a server-client which the server asks the client for a port and then they starting to listen to the port that given, and this is the loop I got a error and I don't know how to fix it.
server:
import socket
import random
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 1729))
server_socket.listen(1)
(client_socket, server_socket) = server_socket.accept()
done = False
while not done:
port = client_socket.recv(4096)
client_socket.send('i got the port' + port)
port = int(port)
if port != 1:
server_socket.bind(('0.0.0.0', port))
continue
else:
done = True
if __name__ == '__main__':
main()
client:
import socket
import random
def main():
print 'hi at anytime enter 1 to break the loop'
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 1729))
done = False
while not done:
port = client_socket.send(raw_input("enter port:"))
data = client_socket.recv(4096)
print data
port = int(port)
if port != 1:
client_socket.connect(('127.0.0.1', port))
continue
else:
done = True
client_socket.close()
if __name__ == '__main__':
main()
the error output for the server:
File "C:/Cyber/ServerFolder/ports_carrousel.py", line 18, in main
server_socket.bind(('0.0.0.0', port))
AttributeError: 'tuple' object has no attribute 'bind'
In your main function, you do the following:
(client_socket, server_socket) = server_socket.accept()
but, server_socket.accept() actually returns two objects. The first, is a socket object, and the second one is a tuple that contains (sourceIPString, sourcePort).
Thus, by using this line of code, outlined above, you are essentially overriding the server_socket by a tuple object.
Notice that later, in line 18, you are trying to access the "bind" function of a socket, but, using a reference to a tuple object, that does not implement such a function.
What you should be doing is something along the lines of
(client_socket, client_connection_info) = server_socket.accept()
and adjust your code accordingly.
Just a couple of things wrong here. First, accept returns a 2-tuple containing the newly-connected socket, and the client's address (which is itself a 2-tuple of IP address and port number). It does not return two sockets. But you're overwriting your server_socket variable with the second returned value. That doesn't make sense and it's why the interpreter is telling you that the 2-tuple has no bind attribute: it's not a socket object. The accept call should look something like this:
client_socket, client_addr = server_socket.accept()
Next, after receiving the new port number from the client, you must create a new socket (you cannot re-use the same listening socket), then bind that new socket to the new port, then listen; finally you can accept a new client connection from the new listening socket.
You should also close sockets you're finished with so that you don't continually leak file descriptors. That means each time you receive a new port number from the client, you should close the client socket, and the listening socket, then create a new listening socket (and bind and listen), then accept the new client socket.
Altogether that will mean restructuring your code in the server significantly. You need to pull the creation of a listening socket down into your main while not done loop.
Another thing to keep in mind. On the client side, immediately after sending the port number to the server, you're attempting a connect to that new port number. However, it's almost certain that your connect request will reach the server before the server has had a chance to create a new listening socket, and bind it. So your client will either need to delay a moment before attempting to connect, or it will need to have logic to retry the connect for some period of time.
EDIT:
Also, you must create a new socket on the client side too when reconnecting. Once a stream socket has been bound to a port (which also happens automatically when you connect), you can never use it to bind or connect to a different address/port.

How to open a Port on Server

I am new to opening a port and server side programming. And I am trying to open a port on my server in python and then form an iOS app get some data from that port. I have done some research and know I can open a port like this
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
But my question is lets say I just wanted to retrieve a simple string from this port how do I add that string to this open port, I have found some ways to get data from the port in iOS like this library https://github.com/armadsen/ORSSerialPort but how do I put the data like a string on the open port?
Thanks for the help in advance.
When you call the method s.accept() it will return the socket object as the first return. You can call socket.rescv method to read data -
data = c.recv(1024)
But do remember this is a blocking call. For more information, you can read this post.

Python server-client

I need some help. I have a simple server:
host="localhost"
port=4447
from socket import *
import thread
def func():
while 1:
data = conn.recv(1024)
if not data:
continue
else:
print("%s said: %s")%(player, data)
conn.close()
s=socket(AF_INET, SOCK_STREAM)
s.bind((host,port))
s.listen(2)
print("Waiting for clients on localhost, port %s")%port
while 1:
conn, addr = s.accept()
player = addr[1]
print(conn)
thread.start_new_thread(func,())
And a simple client:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 4447
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while 1:
data = raw_input("Input: ")
s.send(data)
So when I connect to the server I can type anything and it is printed in the server's terminal. When I open another terminal and start second client I can also type anything and it is sent to the server, but when I go back to the first client's terminal and type several messages, it returns:
Traceback (most recent call last):
File "Client.py", line 18, in <module>
s.send(data)
socket.error: [Errno 32] Broken pipe
So I fixed that with adding conn as a parameter in func(), but I don't understand why this error happened? Could anyone please explain it to me?
Thanks!
Your func, apart from needing a better name, uses global state in your program to communicate with a client. No matter how many threads you start to handle client connections, there's still only one global conn variable. Each time a new client connects, your main thread loop rebinds conn to the new connection. The old socket is thrown away and automatically closed by the Python runtime.
You can fix this by removing the use of global variables to track per-connection state. A better route to explore, though, is Twisted.

Receiving files python socket server

I was trying to create a python socket server that could send and receive data, so I created a socket on the server using the code here:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 1208))
serversocket.listen(5)
(client,(ip,port)) = serversocket.accept()
Then I tried to create a sample connection from my machine by going to command prompt and typing
telnet www.filesendr.com 1208
However, the console simply replies with "Could not open connection to the host, on port 1208...Connection failed." I went back over my code but couldn't identify the problem. Any help would be greatly appreciated.
I think part of the problem is that after you accept the connection you don't do anything else. Once the accept happens, you get to the end of the script, python exits and closes all open file handles (including the socket you just opened). If you want to be able to talk to yourself through telnet, try something like this:
import socket
import select
import sys
port = 1208
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind(('',port))
listener.listen(128)
newSock, addr = listener.accept()
while True:
r,w,e = select.select([newSock,sys.stdin],[],[])
if newSock in r:
data = newSock.recv(4096)
sys.stdout.write(data)
if sys.stdin in r:
newSock.send(sys.stdin.readline())

Categories

Resources