I am trying to create a basic instant message program that uses a p2p (peer-to-peer) connection so it will not need a server. I am pretty sure nothing is wrong, but every time I run the client program I have created, I get this error:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
NameError: global name 'SOL_SOCKET' is not defined
Here is the program:
import socket
def Receiver():
# Create socket that supports IPv4, TCP Protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created."
# Requests for IP of host (DNS)
dns = "localhost"
HOST = ''
PORT = 25395
try:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
except socket.error as serror:
print "socket error"
s.bind((HOST, PORT)) # Listens on all interfaces...
print 'Listening on port 25565'
s.listen(True) # Listen on the newly created socket...
conn, addr = s.accept()
print 'Connected in port 25565'
data = conn.recv(1024)
print data
s.close()
def Sender():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = "localhost"
HOST = socket.gethostbyname(dns)
port = 25565
# Connect to server
s.connect((host,port))
print "Socket connected to " + dns + " on IP " + host
# Assign message to be sent to server to a variable
message = raw_input("Message to be sent to server: ")
#Send the actual message to server
s.sendall(message)
print "Message sent successfully"
s.close()
input = raw_input('S is send, R is receive: ')
if input == 's':
Sender()
if input == 'r':
Receiver()
I have tried removing s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) but it tells me that I cannot use 2 sockets on the same port when there isn't 2 sockets using the same port.
In your code:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
do like:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ^^^^ added ^^^
because you imported just socket, check following code pieces:
>>> import socket
>>> SOL_SOCKET
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SOL_SOCKET' is not defined
>>> socket.SOL_SOCKET
1
Related
I have a W5100S-EVB-Pico which is basically a Pi Pico with an ethernet port. I would like to send commands to it over a TCP socket connection. Basically I want to control hardware over ethernet using this board.
The W5100 board should be a server that accepts connections/commands.
I plan on programming a GUI in Python to send commands
I'm running this micropython version on it.
Python version 3.7
But this is the problem now: The code below keeps giving me this error: 'OSError: [Errno 107] ENOTCONN'
EDIT_01: It seems like I'm closing the connection too soon from the client side ()
EDIT_02: Do I need some kind of acknowledgement from the server before closing? Or, what are possible ways to implement this kind of communication?
Thanks for reading!
Here's the code and an explanation of what's going on:
The code on the W5100-EVB-Pico:
from machine import Pin, SPI
import network
import usocket as socket
# Only needed for static IP setup:
ip_address = '192.168.1.20'
subnet = '255.255.255.0'
gateway = '192.168.1.1'
dns = '8.8.8.8'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_port = 8080
# Init ethernet
def init_ethernet():
spi = SPI(0, 2_000_000, mosi=Pin(19), miso=Pin(16), sck=Pin(18))
nic = network.WIZNET5K(spi, Pin(17), Pin(20))
# Static IP:
# nic.ifconfig((ip_address, subnet, gateway, dns))
# DHCP:
nic.active(True)
while not nic.isconnected():
pass
ip_address = nic.ifconfig()[0]
subnet = nic.ifconfig()[1]
gateway = nic.ifconfig()[2]
dns = nic.ifconfig()[3]
print('Connected:')
print('IP ', ip_address)
print('Subnet ', subnet)
print('Gateway ', gateway)
print('DNS ', dns)
listen()
def listen():
server_socket.bind((ip_address, socket_port))
server_socket.listen(5)
print(f'Listening on {ip_address} port {socket_port}')
while True:
print('>>>This should print once and it does')
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
client.close()
if __name__ == "__main__":
init_ethernet()
The output when running this is:
netif changed 192.168.1.20
Connected:
IP 192.168.1.20
Subnet 255.255.255.0
Gateway 192.168.1.1
DNS 192.168.1.150
Listening on 192.168.1.20 port 8080
>>>This should print once and it does
>>>Waiting for connection
My Python code:
import socket
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
def test_socket():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(server_address)
message = 'Hello from client'
s.sendall(bytes(message, encoding="utf-8"))
if __name__ == '__main__':
test_socket()
As soon as I run this code the output from the W5100 is:
...
>>>This should print once and it does
>>>Waiting for connection
Traceback (most recent call last):
File "<stdin>", line 55, in <module>
File "<stdin>", line 37, in init_ethernet
File "<stdin>", line 49, in listen
OSError: [Errno 107] ENOTCONN
=============================================
EDIT_01:
I found that when I add 'time.sleep(1)' here:
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
The error does not occur. Am I closing the socket too soon on the Python side?
=============================================
EDIT_02:
I changed this code on the server:
while True:
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
data = client.recv(1024).decode()
print(data)
client.close()
And this on the client:
def test_socket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
message = 'This is a really long message of many bytes and can\n' \
'even be some very long JSON data?\n' \
'which is pretty awesome!\n' \
'Man This is what I was after !!!'
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
However, time.sleep(1) is not the way to go :(
I think I should close the socket after an acknowledgement from the server?
Any hint and tips are welcome,
Thanks!
Ok, the key seems to be error catching in the communication.
This client code works like intended... for now.
import socket
import json
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
commands = [['A', 1, '1234567890_1234567890_1234567890'],
['B', 2, 'hello'],
['C', 3.7],
['D', 4]]
def test_socket():
for c in commands:
send(json.dumps(c))
def send(message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
s.sendall(bytes(message, encoding="utf-8"))
try:
received_data, addr = s.recvfrom(128)
print(received_data, addr)
print(received_data.decode('utf-8'))
except socket.error as error:
print(f'Socket error: {error.errno}')
finally:
pass
if __name__ == '__main__':
test_socket()
im making a Reverse Shell. and in the server.py file i got this error.
i has trying in de socket_bind() s.bind((host, port))
My code:
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error: " + str(msg) + "\n" + "retrying...")
socket_bind()
my error:
Binding socket to port: 90
Traceback (most recent call last):
File "c:/ReverseShell/server.py", line 50, in <module>
main()
File "c:/ReverseShell/server.py", line 47, in main
socket_bind()
File "c:/ReverseShell/server.py", line 21, in socket_bind
s.bind((host, port))
TypeError: an integer is required (got type str)
how can i fix this error?
I know where you get this code. I don't know how to fix it, but you could use the code below for server.
# first import all require module
import socket # For building tcp connection
import os # Using this module for basic operation
os.system ("clear || cls") # it clear the terminal screen
def connect ():
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # START a socket subject s
s.bind (("192.168.0.200", 9999)) # Define IP and Port
s.listen (1) # listen METHOD for pass the parameter as 1
print ('[+] Listening for incoming TCP connection on port 8080')
conn, addr = s.accept () #I want my server to accept CLIENT AND IP ADRESS BY ACCEPT METHOD
print ('[+] We got a connection from: ', addr)# After accpeted, print out the result
ter = 'terminate'
while True: #while connection is true
command = input ("\nShell>") # Get user input and store it in command variable
if ter in command: # If we type terminate command, so close te connection and break the loop
conn.send (ter.encode('utf-8')) #to send data to client with conn.send()
conn.close ()
break
else:
conn.send(str.encode (command)) #here we will send the command to the target send commands from server to client using python socket
client = str(conn.recv(1024).decode("utf-8"))
print (client) # print the result that we got back
def main():
connect()
main ()
Trying to Create Messenger Application within python (cross internet). So far I have successfully been able to send a message to the receiver end and then ping the message back to the user that sent it. However, it does not send the message to all connected users. I think this is because if python is listening for user input the socket cannot receive any data (I might be wrong...).
Below is the client side code:
import socket
host = '**.***.***.***' # Public Ip Hidden
port = 5005 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
b = input("Please enter your message.")
b = b.encode('utf-8')
s.sendall(b)
while True:
data = s.recv(1024)
print('Message Received:', repr(data))
Now below is the server side code:
import socket
import sys
import os
import thread
import threading
from thread import *
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client = ''
clients = set()
clients_lock = threading.Lock()
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#infinite loop so that function do not terminate and thread do not end.
with clients_lock:
clients.add(client)
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
else:
print repr(data)
with clients_lock:
for c in clients:
for d in data:
conn.sendall(data)
print(data.decode("utf-8"))
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
Any Suggestions would be much appreciated.
I've been following examples on a server and client communication within Python but I cannot get the server to constantly listen for new messages, print them and send them back for the client to print it as well. Any ideas what I'm doing wrong?
Server code:
#Imports
import socket
#Define socket address
TCP_IP = '0.0.0.0' # consider all incoming IPs
TCP_PORT = 5000 # port# communicating with the client
BUFFER_SIZE = 1024 # buffer size for receiving data
#Create socket IPv4 TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created"
s.bind((TCP_IP, TCP_PORT))
s.listen(20)
print "Waiting for a Cli_socket..."
#Wait for Cli_sockect
while True:
while True:
# accept Cli_sockection
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
print message
# check that there is a message
if not message:
break
# send message to client
Cli_sock.send(message)
print "Sent message"
s.close()
print "Socket Closed"
Client code:
# a simple client socket
import socket
# define socket address
TCP_IP = '127.0.0.1' # ip of connecting server
TCP_PORT = 5000 # port communicating server
BUFFER_SIZE = 1024 # buffer size receiving data
# create socket IPv4 & TCP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created successfully."
# connect to server
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
while True:
print ("Message to send:")
message = raw_input()
s.send(message)
print "Message sent to server: %s." % message
print ("Message Recv:%s\n" % data)
Your server is waiting for data from the client before sending anything:
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
Your client is waiting for data from the server before sending anything:
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
Thus both wait for each other to send data but nobody does. That's why it hangs.
HELP please i have this code
import socket
from threading import *
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
s.bind((HOST, PORT))
print ('Socket bind complete')
s.listen(10)
print ('Socket now listening')
def listen(conn):
odata = ""
end = 'end'
while end == 'end':
data = conn.recv(1024)
if data != odata:
odata = data
print(data)
if data == b'end':
end = ""
print("conection ended")
conn.close()
while True:
time.sleep(1)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
Thread.start_new_thread(listen,(conn))
and i would like it so that when ever a person comes onto the server it has its own thread. but i can't get it to work please someone help me. :_(
here is the error code:
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:61475
Traceback (most recent call last):
File "C:\Users\Myles\Desktop\test recever - Copy.py", line 29, in <module>
Thread.start_new_thread(listen,(conn))
AttributeError: type object 'Thread' has no attribute 'start_new_thread'
i am on python version 3.4.0 and here is the users code:
import socket #for sockets
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Created')
host = 'localhost'
port = 8888
remote_ip = socket.gethostbyname( host )
print('Ip address of ' + host + ' is ' + remote_ip)
#Connect to remote server
s.connect((remote_ip , port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
while True:
message = input("> ")
#Set the whole string
s.send(message.encode('utf-8'))
print ('Message send successfully')
data = s.recv(1024)
print(data)
s.close
The API you're using has moved from thread to _thread, so you'll need to do;
import _thread
The call is on the _thread module and requires a tuple as a second argument, so the correct line to start the thread would be;
_thread.start_new_thread(listen,(conn,))
IMHO, you're on the right track trying to use threading instead though, but that API works differently so you'll have to rewrite the code to make it work. A very brief description how it's used is for example available here.