This the server code using sockets. I have deployed in the AWS server. I am trying to access it from local machine which is outside AWS. I have opened the TCP port 10000 in the security group (custom TCP) to my local IP. But getting a error as shown below.
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
This is the client code (trial-sockets.py) i am using. The error i am getting is given below
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print(sys.stderr, 'connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# Send data
message = 'This is the message. It will be repeated.'
print(sys.stderr, 'sending "%s"' % message)
sock.sendall(message)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print >>sys.stderr, 'received "%s"' % data
finally:
print >>sys.stderr, 'closing socket'
sock.close()
Error Message:
arunachalam#LV-SL306:~/Documents/aws$ python3 trail-sockets.py
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> connecting to localhost port 10000
Traceback (most recent call last):
File "trail-sockets.py", line 10, in <module>
sock.connect(server_address)
ConnectionRefusedError: [Errno 111] Connection refused
Related
I'm trying a simple send/receiver example on my local machine using TCP. The goal is to open a TCP server and send some data. My setup is Python3.6 on Pycharm IDE. I have enabled parallel run of the sender and receiver scripts.
Here is the Server script:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5005)
print(sys.stderr, 'starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print(sys.stderr, 'waiting for a connection')
connection, client_address = sock.accept()
try:
print(sys.stderr, 'connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print(sys.stderr, 'received "%s"' % data)
if data:
print(sys.stderr, 'sending data back to the client')
connection.sendall(data)
else:
print(sys.stderr, 'no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
And here is the client script:
import socket
TCP_IP = 'localhost'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE.encode('utf-8'))
I verified that both scripts are running and I've used the debugger to parse each line on the sender side. I get no errors but I also don't see that the server receives anything.
EDIT:
I have used an example code from this page
Server:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data + b' from server')
Client:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
And I get the expected result:
Received b'Hello, world from server'
Hmm, the client scripts ends immediately after sending its data... This is at least dangerous! Race conditions could cause the connection to be destroyed before anything has been correctly received by the peer. The robust way would be to use a graceful shutdown client side:
...
s.send(MESSAGE.encode('utf-8'))
s.shutdown(socket.SHUT_WR) # tell peer we have nothing more to send
while True:
data = s.recv(256)
if len(data) == 0: # but keep on until peer closes or shutdowns its side
break
After that, I could test that your server script could correctly receive and send back the message:
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> starting up on localhost port 5005
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> connection from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b'Hello, World!'"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> sending data back to the client
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b''"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> no more data from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection
I'm trying to route my outbound udp packets through an external proxy server (not expecting traffic to return atm). The traffic makes it to the destination server, however the source ip address in the packets is my client's ip address rather than the external proxy's.
What am I doing wrong?
from scapy.all import *
import socks, socket
sent = False
def intercept(pkt):
if pkt.haslayer(UDP):
s = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM)
s.setproxy(socks.PROXY_TYPE_SOCKS5, "proxy-server-ip", 19012, True)
dst_addr = pkt[IP].dst
global sent
if not sent:
dst_port = pkt[UDP].dport
address = (dst_addr, dst_port)
s.sendto(bytes("test", 'utf-8'), address)
sent = True
def main():
sniff(iface='ens3', prn=intercept)
if __name__ == '__main__':
main()
The way I'm checking the udp packets are with a small client/server configuration.
Client:
import socket
import sys
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('server-ip', 10000)
message = 'This is the message. It will be repeated.'
try:
# Send data
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, server_address)
# Receive response
print >>sys.stderr, 'waiting to receive'
data, server = sock.recvfrom(4096)
print >>sys.stderr, 'received "%s"' % data
finally:
print >>sys.stderr, 'closing socket'
sock.close()
Server:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('0.0.0.0', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
while True:
print >>sys.stderr, '\nwaiting to receive message'
data, address = sock.recvfrom(4096)
print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data
if data:
sent = sock.sendto(data, address)
print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)
I was trying to create an easy client/server program with the module socket. it is the basic tutorial for every standard socket implementation.
#Some Error in sock.accept (line 13) --> no fix yet
import socket
import sys
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print >>sys.stderr, 'starting up on %s' % host
serversocket.bind((host, 9999))
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#listening for incoming connections
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection , client_address = serversocket.accept()
try:
print >>sys.stderr, 'connection from', client_address
#Receive data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr,'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
#Clean up the connection
#Will be executed everytime
connection.close()
The output it gives is
C:\Python27\python27.exe C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py
starting up on Marcel-HP
waiting for a connection
Traceback (most recent call last):
File "C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py", line 16, in <module>
connection , client_address = serversocket.accept()
File "C:\Python27\lib\socket.py", line 206, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 10022] Ein ung�ltiges Argument wurde angegeben
Before accepting any connections, you should start to [listen()][1] to new connections.
Here is the basic example from python documentation :
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creation of the socket
s.bind((HOST, PORT)) # We tell OS on which address/port we will listen
s.listen(1) # We ask OS to start listening on this port, with the number of pending/waiting connection you'll allow
conn, addr = s.accept() # Then, accept a new connection
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
So, in your case, you only miss a serversocket.listen(1)right after the or serversocket.setsockopt(...)
I am having a multi-client server which listens to multiple clients. Now if to one server 5 clients are connected and I want to close the connection between the server and just one client then how am I going to do that.
My server code is:
import socket
import sys
from thread import *
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,msg:
print "Socket Creation Error"
sys.exit();
print 'Socket Created'
host = ''
port = 65532
try:
s.bind((host, port))
except socket.error,msg:
print "Bind Failed";
sys.exit()
print "Socket bind complete"
s.listen(10)
print "Socket now listening"
def clientthread(conn):
i=0
while True:
data = conn.recv(1024)
reply = 'OK...' + data
conn.send(reply)
print data
while True:
conn, addr = s.accept()
start_new_thread(clientthread,(conn,))
conn.close()
s.close()
I have a problem, whenever I try to run this python script on an Raspberry PI:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
I get this error:
File "server.py", line 20
try:
^
IndentationError: unexpected indent
Could you please tell me what's wrong here? The script is supposed to create a simple TCP/IP server, and I have no such problems with the client, so I really don't understand where is my mistake/s...
One of the unfortunate side-effects of Python's use of whitespace for denoting blocks is that sometimes you get scripts that have tabs and spaces mixed up throughout the source code.
Since this script is pretty small, you could try deleting the whitespace preceding each line's code and then reindent it properly.