2013-03-11 71 views
0

我必須更改一個網絡驅動程序(在實時操作系統上)以嗅探PTP幀(它是具有特殊數據字段的UDP幀)並更改一些數據。我需要更新網絡驅動程序(R8168)中的數據。這樣做我必須在發送幀之前修改CRC字段。 我找過一些例子,但沒有人工作。我想這在使用htons或ntohs的行中是錯誤的:我不知道我是否必須使用網絡字節順序或主機字節順序。設置UDP校驗和字段(在網絡驅動器端)

unsigned int calc_checksum(unsigned char *pcBuf, unsigned short usLength, unsigned int uiSum) 
{ 
    unsigned short i, usTmp ; 
    /* Checksum all the pairs of bytes first... */ 
    for (i = 0; i < (usLength & ~1U); i += 2) 
    { 
     usTmp = *((unsigned short *)(pcBuf + i)) ; 
     uiSum += (unsigned short)ntohs(usTmp) ; 
     if (uiSum > 0xFFFF) 
      uiSum -= 0xFFFF ; 
    } 
    /* 
    * If there's a single byte left over, checksum it, too. 
    * Network byte order is big-endian, so the remaining byte is 
    * the high byte. 
    */ 
    if (i < usLength) 
    { 
     uiSum += pcBuf[i] << 8 ; 
     if (uiSum > 0xFFFF) 
      uiSum -= 0xFFFF ; 
    } 
    /*.*/ 
    return uiSum ; 
} 

/* Recalculate UPD checksum */ 
usTmp = sizeof(TUdpHeader) + sizeof(TPTPSyncData) ; 
uiSum = calc_checksum((unsigned char *)(&pPTPFrame->udpHeader.sport), 
    sizeof(TUdpHeader) + sizeof(TPTPSyncData), 
    calc_checksum((unsigned char *)(&pPTPFrame->ipHeader.saddr), 
     2 * sizeof(unsigned int), IP_UDP + htons(usTmp))) ; 
// Return the one's complement of sum 
usTmp = (~uiSum) & 0xFFFF ; 
pPTPFrame->udpHeader.checksum = htons(usTmp) ; 

注:

  • pPTPFrame是一個指針,指向全幀(EthHeader + IpHeader +
    UdpHeader +數據)
  • IP_UDP = 17
  • TPTPSyncData是數據結構

非常感謝。 Emanuele。

回答

0

這是正確的版本:

/* Recalculate UPD checksum */ 
pPTPFrame->udpHeader.checksum = 0 ; 
uiSum = calc_checksum((unsigned char *)(&pPTPFrame->udpHeader.sport), 
    sizeof(TUdpHeader) + sizeof(TPTPSyncData), 
    calc_checksum((unsigned char *)(&pPTPFrame->ipHeader.saddr), 
     2 * sizeof(unsigned int), IP_UDP + sizeof(TUdpHeader) + sizeof(TPTPSyncData))) ; 
// Return the one's complement of sum 
usTmp = (~uiSum) & 0xFFFF ; 
pPTPFrame->udpHeader.checksum = htons(usTmp) ; 

問題解決了!