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

0

Here is a snippet of 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()

Since I'm in a program in Tkinter, I asked Python to take the text of two entries, one for the host and one for the input, but when you paste the text from a Form it comes as a string and the bind socket only accepts integers to do the assignment. How do I convert the string to int ?

Error:

  

sockobj.bind (int (Host, Port)) TypeError: 'str' object can not be interpreted as an integer.

asked by anonymous 03.01.2017 / 20:13

1 answer

1

If you need the Port to be an integer, then do:

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

int ()

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

You can make sure you have to "integer" 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 error you put in a recent issue, already after this answer that was about another question, happens because you are trying to transform two variables into integer, int(Host, Port) , it can not be because in the bind method enter as argument a tuple (host, port) where the host is a string and the port is an integer, ie you have to do only:

sockobj.bind((Host, Port))

In that port it will be an integer, with the way I put it above, Host = int(self.Txt1.get())

    
03.01.2017 / 20:17