I am making a simple python client for a server client architecture. The problem arises when i convert an integer into a string in C and send it over UDP to python client and try to convert it into integer, exception is raised. I thought it might be because of null terminated string in C, so i even tried eliminating the null terminator but no joy. Any help would be highly appreciated.
Python (client) code snippet where i am receiving the information from server.
while True:
try:
p_ort = client_socket.recvfrom(1024)
portnumber = p_ort[0]
portnumber.strip()
#portnumber = portnumber[:-1]
#portnumber.rstrip("\0")
#this is where i try to convert the string into integer but the exception is thrown
try:
port_number = int(portnumber)
except:
print "Exception"
except:
print "timeout!"
break
This is my code snippet from server where i am sending the values to client.
void sendDataToClient( int sfd , int index )
{
char portNum[9] = {0};
sprintf( portNum , "%d" , videos[index].port ); //videos[index].port is an integer
if( sendto( sfd , &( portNum ) , 9 , 0 , (struct sockaddr *)&client , len ) == -1 )
{
perror( "sendto()" );
}
printf("\nClient Stuff sent!\n");
}
You probably just need to strip off the null first.
For example:
portnumber = int(portnumber.strip('\x00'))
Is how I usually strip off null terminators. It would be hard to know if this is the correct approach though without seeing a print of portnumber.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.