Why does this not connect me to my server? [closed] - python

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 2 years ago.
Improve this question
I am trying to establish a connection to server.py but client.py outputs this error
Traceback (most recent call last):
File "C:\Users\Nathan\Desktop\Coding\Langs\Python\Projects\Chatting Program\Client.py", line 15, in <module>
clientsocket.connect((host, port)) # Connects to the server
TypeError: an integer is required (got type str)
Here is my code...
## CLIENT.PY
from socket import *
import socket
host = input("Host: ")
port = input("Port: ")
#int(port)
username = input("Username: ")
username = "<" + username + ">"
print(f"Connecting under nick \"{username}\"")
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates socket
clientsocket.connect((host, port)) # Connects to the server
while True:
Csend = input("<MSG> ") # Input message
Csend = f"{username} {Csend}" # Add username to message
clientsocket.send(Csend) # Send message to ONLY the server
If there is an issue with my server.py then here is the code to that
## SERVER.PY
from socket import *
import socket
import select
host_name = socket.gethostname()
HOST = socket.gethostbyname(host_name)
PORT = 12345
print(f"Server Info\nHOST: {HOST}\nPORT: {PORT}")
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((HOST, PORT))
serversocket.listen(5)
clientsocket, address = serversocket.accept()
print(address)
with clientsocket:
while True:
Srecv = clientsocket.recv(1024)
print(f"{username} - {address}: {Srecv}")
# Add server time to message before sending
clientsocket.sendall(Srecv)
I have tried converting host and port into str, int, and float, but it only successfully converts into str. Any help would be greatly appreciated. Thanks in advance!

The compile error is pretty fair: input() returns a string for the port number, whereas your function needs an integer. You can fix that by casting the port to an integer - your comment is close:
port = int(port).

If you look at the python documentation, input() always returns a string. The second value in the tuple passed to clientsocket.connect() must be a integer, however, you are passing a your string value. You must cast your port first, with the following code:
port = int(port).
#OR
port = int(input("Port: "))
Always check the docs!

Related

Unable to recvfrom UDP client, bytes object has no attribute recvfrom

I am a newbie to socket programming and I want to send two numbers from client side to server side in UDP and the server will return the product of the two numbers.
When I send the numbers from the client side, there is an error on the server side that "bytes object has no attribute recvfrom".
This is my code
Client side
from socket import socket, AF_INET, SOCK_DGRAM
c = socket(AF_INET, SOCK_DGRAM)
c.connect(('localhost', 11111))
num1 = input('Input a number: ')
num2 = input('Enter a second number: ')
c.sendto(num1.encode('utf-8'), ('localhost', 11111))
c.sendto(num2.encode('utf-8'), ('localhost', 11111))
print(c.recvfrom(1024).decode())
Server side
from socket import socket, AF_INET, SOCK_DGRAM
s = socket(AF_INET, SOCK_DGRAM)
print('Socket created!')
s.bind(('localhost', 11111))
while True:
c, addr = s.recvfrom(1024)
num1 = c.recvfrom(1024)
num2 = c.recvfrom(1024)
print('Received from client having address:', addr)
print('The product of the numbers sent by the client is:', num1*num2)
s.sendto(bytes('***Welcome To The Server***', 'utf-8'))
This is the error that I get:
Exception has occurred: AttributeError
'bytes' object has no attribute 'recvfrom'
File "C:\Users\kryptex\Downloads\Compressed\attachments\udpserv1.py", line 11, in <module>
num1 = c.recvfrom(1024)
c, addr = s.recvfrom(1024)
num1 = c.recvfrom(1024)
num2 = c.recvfrom(1024)
c are the bytes returned by the s.recvfrom. You likely meant s.recvfrom instead of c.recvfrom. Hint: give your variables more clear and longer names which describe their actual function.
Apart from that it is unclear to me what the intend of c, addr = s.recvfrom(1024) actually is, since there is no matching send on the client side. I have the feeling that you are confusing TCP and UDP sockets and tried to implement some kind of TCP accept here, matching the c.connect on the client side. This is wrong though.

Socket is Showing All Ports closed

I was trying to scan ports through socket but it's show all ports closed. Here is my code:
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = input(" Please Input Ip address To Scan ")
#port = input(" ENter The Port ")
def portscanner(host):
for port in range(1,150):
if sock.connect_ex((host,int(port))):
print(f"{port} Is Closed")
else:
print("port is open")
portscanner(host)
Try creating a connection inside the forloop. And make sure that the input is in valid form.
You can do that using
try and catch near the sock.connect_ex to check whether you are actually sending valid host or not.
To make things faster you can use settimeout(0.25) inside the for loop too.
I meant to do this -
for port in range(start, end):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(.25)
result = sock.connect_ex((host, port))
if result == 0:
print(port,'port is open')
sock.close()

Socket Programming Server With (Ip,port) as variable

HI I want to have my ip and port as user input in my server but i get some errors i cant handle please help me ...
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input("Enter The Server Ip: ")
port = input("Enter The Server Port: ")
serversocket.bind((host, port))
serversocket.listen(10)
while True :
clientsocket, address = serversocket.accept()
print("Received Connection From %s" % str(address))
message = 'Connection Established' + "\r\n"
clientsocket.send(message.encode("ascii"))
clientsocket.close()
Error :
line 11, in <module>
serversocket.bind((host, port)) # Host will be replaced with IP, if changed and not running on host
TypeError: an integer is required (got type str)
or some times i get :
TypeError: an integer is required (got type str)
input() gives you port as string but socket needs it as integer
port = int(port)

Using GET/ filename.html HTTP ......... python serve client

Hopefully I can make this somewhat clear. I have to create a server and client in python that sends HTTP GET request to each other. Now I created a basic server/client program and now my goal is to send the server a HTTP GET request(from an html file I have saved) and the server to display the content.
Example Server would display something like
Date:
Content Length:
content Type:
As of now when I run the client and type GET / filename.html HTTP/1.1\n\r the server does not display. When I type that exact command in just a Linux shell it displays perfectly. How can I do this in a client and server. Hopefully this makes sense. Here is my client and server.
#CLIENT
import socket
import sys
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(s.recv(1024))
inpt = input("type")
b = bytes(inpt, 'utf-8') #THIS SENDS BUT SERVER DOESDNT RECIEVE
s.sendall(b)
print("Message Sent")
#SERVERimport socket
import sys
host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send(b"Server Approved")
print(repr(addr[1]) + ":" + c.recv(1024).decode("UTF-8"))
c.close()
I want to type something like this to my server and display its content
GET / google.com HTTP/1.1\r\n
The error message is so straightforward, just read it to fix the code that doesn't work.
Traceback (most recent call last):
...
print(repr(addr[1]) + ":" + c.recv(1024))
TypeError: must be str, not bytes
Add .decode("utf-8"):
print(repr(addr[1]) + ":" + c.recv(1024).decode("utf-8"))
And more clear is to use str() instead of repr(). You can read about the differences between these two here: Difference between __str__ and __repr__ in Python.
print(str(addr[1]) + ":" + c.recv(1024).decode("utf-8"))

Trying to have multiple people connected to a Socket in python [duplicate]

This question already has answers here:
Python Socket Multiple Clients
(6 answers)
Closed 5 years ago.
Im trying to have multiple clients be able to connect to a server however when a second user connects it kicks the other client off the server as you cant have 2 clients connected to a socket and i was wondering if there was anything around this.
server.py
import socket
def Main():
host = '10.41.13.228'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
name = input("Please Enter your name - ")
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
data = c.recv(1024).decode('utf-8')
print(data)
c.close()
if __name__ == '__main__':
Main()
Client.py
import socket
def Main():
host = '10.41.13.228'
port = 5000
s = socket.socket()
s.connect((host, port))
name = input("Please enter your name - ")
message = input("-> ")
while True:
while message != 'q':
ToSend = (str(name) + " - " + str(message))
s.sendall(ToSend.encode('utf-8'))
message = input("-> ")
s.close()
if __name__ == '__main__':
Main()
The problem i noticed in your code is s.listen method. Where you are listening to only one client connection. You could increase the amount to have more clients connected to the server.
As described in the example from the docs:
Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().
Therefore, there are two missing parts in your code.
As already commented, your listen() method should take a 2 as argument (as you intend to have 2 clients).
You should call accept() twice. Remember to keep in mind the comment of the example. Quoting again:
note that the server does not sendall()/recv() on the socket it is
listening on but on the new socket returned by accept()
Out of topic. It is indeed a good practice to have a keyword such as 'exit' to break from the loop of your server once recieved.

Categories