Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I am trying to understand how to interact with python socket server meant for python socket client but in go
please rewrite python client in go language with same functionality without changing server code, that should be enough for me to understand how to do it
server:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 5556
server.bind((host,port))
server.listen()
client, adress = server.accept()
#1
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#2
client.send("send2".encode('utf-8'))
#3
variable2 = client.recv(4096).decode('utf-8')
print(variable2)
#4
client.send("send4".encode('utf-8'))
client:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 5556
client.connect((host, port))
#1
client.send("send1".encode('utf-8'))
#2
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#3
client.send("send3".encode('utf-8'))
#4
variable2 = client.recv(4096).decode('utf-8')
print(variable2)
Close the connection to terminate the stream of data from the server to the client:
⋮
client.send("text1".encode('utf-8'))
client.close()
Read to EOF in the client program:
⋮
message, err := io.ReadAll(conn)
checkError(err)
fmt.Println(string(message))
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I want to make it so it takes IP addresses from target list and scans port 22 and if it is open print(port 22 open)
also it takes proxies from a list and proxy's connection
Heres code:
import socket
import sys
import requests
ips = open('targets.txt')
x = ips.readline()
with open('proxyf.txt', 'r') as f:
proxy = f.read().splitlines()
proxies = {
'http': (proxy,)
}
print('Port 22 Bounty Hunter')
def attack():
try:
for port in range(22, 23):
requests.get(url='https://google.com', proxies=proxies)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((x, port))
if result == 0:
print("Port 22 is Open")
sock.close()
except socket.gaierror:
print('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print("Couldn't connect to server")
sys.exit()
for targets in range(100):
attack()
what is the error?
This question already has answers here:
C - How to limit the number of inbound connections in a server when using select()
(3 answers)
Java SocketServer is not limited by backlog value
(1 answer)
listen() ignoring backlog value
(1 answer)
listen() ignores the backlog argument?
(2 answers)
Closed 1 year ago.
I'm trying to limit a Python server to only accept a connection from one client, but I'm noticing that the Python server always accepts one too many connections. Here is the server code:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(0)
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
while True:
time.sleep(1000)
clientsocket.send(bytes("Welcome to server 1!", "utf-8"))
I would expect this to only allow one client connection at a time, since there is not allowed to be any in the queue (s.listen(0)). However, I'm finding that this code allows me to connect two clients before getting an error. Here are my clients connecting:
>>> import socket
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The first client is accepted, which is expected. The second client successfully connects, which I would not expect since the server already has a connection and 0 connections are allowed in the queue. We do not fail until the third client tries to connect and is denied.
If we up the listen() argument to 1, we are allowed 3 connections (1 current, 2 in the queue). If we up it to 2, we are allowed 4 connections (1 current, 3 in the queue). This pattern continues.
How can I specify that my server should allow allow 1 connection and not hold any in the queue?
Regardless of the documentation:
socket.listen([backlog])
Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.
Testing indicates the minimum is 1 for unaccepted connections, and not backlog + 1. This may be OS-dependent. I'm using Windows 10. Note I'm not accepting any connections below, just connecting until they are refused.
In [1]: from socket import *
...: for backlog in range(-1,6):
...: s=socket()
...: s.bind(('',5000))
...: s.listen(backlog)
...: c=[]
...: try:
...: while True:
...: a=socket()
...: a.connect(('localhost',5000))
...: c.append(a)
...: except ConnectionRefusedError:
...: print(f'{backlog=} successful_connections={len(c)}')
...:
backlog=-1 successful_connections=1
backlog=0 successful_connections=1
backlog=1 successful_connections=1
backlog=2 successful_connections=2
backlog=3 successful_connections=3
backlog=4 successful_connections=4
backlog=5 successful_connections=5
Which makes sense. You need at least one unaccepted connection queued or there would be nothing to .accept().
If you want only one accepted connection, call .accept() serially and close it before accepting another. The client can use timeouts if it connects, sends a query and doesn't get a response in a set amount of time.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm testing responses for BrokenPipeError between a server application and a client application. I'm working on responses from the server to handle the BrokenPipeError appropriately. What would be the easiest way to break the connection (from the client side) in order to reproduce this error?
I am using standard python sockets as the connection.
TLDR: just exit the client while connected.
The simplest way I can see to break the connection from the client is to just close the client while you have a connection.
I quickly coded this example of a simple server-client in Python to demonstrate:
server.py:
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind(("192.168.1.111", 6969))
serverSocket.listen(1)
conn, addr = serverSocket.accept()
while True:
print(conn.recv(1024).decode("utf-8"))
conn.send("Response".encode("utf-8"))
client.py:
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(("192.168.1.111", 6969))
while True:
data_out = input("> ").encode("utf-8")
if len(data_out) > 0:
clientSocket.send(data_out)
print(clientSocket.recv(1024).decode("utf-8"))
This will let the client send some text and receive "Response" from the server, which it prints. The server will print whatever it receives and send back "Response". Simple.
All I had to do was exit the client.py while there was an active connetion and the server gave me this:
Traceback (most recent call last):
File "server.py", line 14, in <module>
conn.send("Response".encode("utf-8"))
BrokenPipeError: [Errno 32] Broken pipe
There's your broken pipe.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
#!/bin/python
import socket
HOST = "localhost"
PORT = 30002
list = []
passwd = "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ"
for i in range(1000, 9999):
list.append(i)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
iter = 0
data = s.recv(1024)
# Brute forcing loop
while 1:
s.send(passwd + " " + list[iter]
data = s.recv(1024)
if "Fail!" not in data:
print s.recv(1024)
s.close()
else:
print "Not: " + list[iter]
iter += 1
s.close()
I get an invalid syntax on the s.recv call, but I believe that the socket isn't initiating a valid handshake. I can connect to the daemon through netcat.
You miss the parenthesis after the s.send() function
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My Server TCP Code:
import socket
import sys
HOST = ''
PORT = 8031
s = socket.socket()
class BoServer:
def __init__(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
def bind(self):
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
def run(self):
s.listen(10)
print "Socket Listening"
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
while True:
income = conn.recv(4096)
if income != "":
print income
def main():
serv = BoServer()
serv.bind()
serv.run()
if __name__ == "__main__":
main()
My Client TCP Code:
import socket
import sys
def main():
host = ""
port = 8031
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connect to server
s.connect((host,port))
while message != "/e":
#Send Data
message = raw_input("Send >> ")
try:
s.sendall(message)
except socket.error, msg:
print "ERROR %s"%(msg[1])
print "Failed to send."
s.close()
main()
I want to people write my public ip xxx.xxx.xxx.xx on the client and to connect at the server.
When I run the Server, others can't connect to my Server. I can only access the server with localhost or my local IP.
Everyone that tries to connect receive this ERROR:
Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time.
What am I doing wrong ?