我正在尝试使用MD5_Init
,MD5_Update
等功能。
我尝试从服务器中的文件getline
发送,并在客户端I read
100个字符发送。
这是我最重要的代码部分: server.c
connfd = accept(listenfd,(struct sockaddr*) NULL,NULL);
if(sposob == 1)
{
while( (read = getline(&line,&len,stream) ) != -1)
{
write(connfd,line,read); // raad = zwraca wartosc ile
sleep(czas); // mala precyzja
line[read-1] = '\0';
if( !odbierz_i_policz_md5(connfd,line,read) )
{
perror("Blad MD5 \n");
}
}
}
// my function
char *str2md5(const char *str, int length) {
int n;
MD5_CTX c;
unsigned char digest[16];
char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n) {
snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
}
return out;
}
int odbierz_i_policz_md5(int gniazdo,char *str1, int length)
{
char *out = (char*)malloc(33);
char *wiad;
if(recv(gniazdo, out, 33,0) != -1)
{
wiad = str2md5(str1,length) ;
if (strncmp (wiad,out,33) == 0)
{
free(out);
free(wiad);
return 1;
}
else
{
free(out);
free(wiad);
return 0;
}
}
else{
fprintf(stdout,"Recv error! \n");
exit(EXIT_FAILURE);
}
}
client.c
#define BUFLEN 100
while( (n = read(sockfd,recvBuff,sizeof(recvBuff-1))) > 0 )
{
char *wiad;
recvBuff[n] = 0;
write(fd,recvBuff,n);
/* if(fprintf(stdout,"%s",recvBuff) == EOF)
{
perror("fprintf");
}
fflush(stdout);
*/
// odebral - teraz wyslac
wiad = str2md5(recvBuff,n);
fprintf(stdout,"Wiadomosc %s \n",recvBuff);
if( send(sockfd,wiad,33,0) == -1 )
{
fprintf(stderr, "Failure Sending Message\n");
}
free(wiad);
}
我的问题: 我在客户端和服务器上有不同的MD5!我认为MD5应该在两个站点(客户端,服务器)都有相同的消息。我的错误在哪里?如何改进我的代码?