[英]Conversion of null terminated string to Int in Python
I am making a simple python client for a server client architecture. 我正在为服务器客户端体系结构制作一个简单的python客户端。 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.
当我将整数转换为C中的字符串并通过UDP将其发送到python客户端并尝试将其转换为整数时,就会出现问题,从而引发异常。 I thought it might be because of null terminated string in C, so i even tried eliminating the null terminator but no joy.
我以为可能是因为C中的null终止字符串,所以我什至尝试消除null终止符,但没有任何乐趣。 Any help would be highly appreciated.
任何帮助将不胜感激。
Python (client) code snippet where i am receiving the information from server. 我从服务器接收信息的Python(客户端)代码段。
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. 您可能只需要先去除null。
For example: 例如:
portnumber = int(portnumber.strip('\x00'))
Is how I usually strip off null terminators. 我通常是如何去除null终止符的。 It would be hard to know if this is the correct approach though without seeing a print of portnumber.
即使没有看到端口号的打印,也很难知道这是否是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.