How to convert a string to an integer in a socket program?

Asked

Viewed 678 times

0

Here is an excerpt from the code:

def CriarServer(self):
     Host = self.Txt1.get() 
     Port = self.Txt2.get()

     sockobj = socket(AF_INET, SOCK_STREAM) #Erro

     sockobj.bind((Host, Port))
     sockobj.listen(5)

     while True:

        data = conexão.recv(1024)

        if not data: break

        conexão.close()

As I am in a program in Tkinter, I asked Python to take the text of two inputs, one port and one host, but when you take the text of a Form, it comes as a string and socket bind only accepts integer numbers to do the assignment. As I convert the string to int?

Error:

sockobj.bind(int(Host, Port))Typeerror: 'str' Object cannot be Interpreted as an integer.


  • There were several people giving negative for no reason.

  • Thank you very much, when you give the time I accept the answer.

1 answer

0


As long as you need Port be a whole, then do:

Host = int(self.Txt1.get())

int()

So you have to be sure that the input will be numerical, otherwise it will generate error ValueError: invalid literal for int() with base 10:...

You can make sure you "have to be whole" and adapt to your code like this:

Host = None
while not isinstance(Host, int):
    try:
        Host = int(input('número'))
    except ValueError as err:
        print('numro incorreto')

The mistake you made in a recent issue, after this answer that was about another question, happens because you’re trying to make two variables whole, int(Host, Port), cannot be because in the bind method enters as argument a tuple (host, port) where the host is a string and the port is an integer, that is, you have to do only:

sockobj.bind((Host, Port))

In which port will be a whole, with the way I put up, Host = int(self.Txt1.get())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.