Home > database >  I can't get a response from the server via socket python
I can't get a response from the server via socket python

Time:05-25

  import socket

  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_server:

    socket_server.connect(("77.222.42.207", 1337))
    socket_server.send("get_flag".encode())

    server_unswer = (socket_server.recv(1024)).decode()
    print(server_unswer)

    while (messsage := input("Я: ")) != "exit":
      socket_server.send(messsage.encode())
      messsage = socket_server.recv(1024)
      messsage = messsage.decode()
      print(messsage)

I'm trying to send a string to the server, but I can't send the data and get a response, what's the problem, please help.

When I connect to the server via netcat, everything is fine.

CodePudding user response:

It looks like nothing is wrong with your code.Just create a simple server as shown below and connect your client socket program.

import socket
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM,             
proto=socket.IPPROTO_TCP, fileno=None)
server.bind(('IP address', port))
server.listen(10)
client, _ = server.accept()
    # Instead of a infinite while loop a for loop in given with a count of 10
    for i in range(10):
        data = client.recv(65535).decode()
        print(data)
        client.send(data.encode())
server.close()

Obviously you will have to update socket_server.connect(("77.222.42.207", 1337))

CodePudding user response:

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_server:

  socket_server.connect(("77.222.42.207", 1337))

  server_unswer = (socket_server.recv(1024)).decode()
  print(server_unswer)

  socket_server.send("get_flag\n".encode())

  server_unswer = (socket_server.recv(1024)).decode()
  print(server_unswer)

I was finally able to get a response from the server, it was because NetCat automatically adds \n when sending text and the command on the server worked, but I did not add this character when sending text

  • Related