如何获得UDP校验和?

时间:2014-03-07 21:52:41

标签: c udp

我想从UDP中提取校验和,并将其用作另一个函数的参数。 我有以下代码。

void connection_init()
{
bool sender_registered = false, receiver_registered = false;

int localsockfd, globalsockfd;
struct sockaddr_in localaddr, globaladdr, trolladdr, senderaddr, receiveraddr, cliaddr;

localsockfd = socket(AF_INET, SOCK_DGRAM, 0);
globalsockfd = socket(AF_INET, SOCK_DGRAM, 0);

//localaddr -- This address and port is used by tcpd to receives data from local client or server process
bzero(&localaddr, sizeof(localaddr));
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(14683); 
localaddr.sin_addr.s_addr = htonl(INADDR_ANY);

//globaladdr -- This address and port is used to communicate with troll process 
bzero(&globaladdr, sizeof(globaladdr));
globaladdr.sin_family = AF_INET;
globaladdr.sin_port = htons(14684);
globaladdr.sin_addr.s_addr = htonl(INADDR_ANY);


//trolladdr -- Troll process address
bzero(&trolladdr, sizeof(trolladdr));
trolladdr.sin_family = AF_INET;
trolladdr.sin_port = htons(14685);
inet_pton(AF_INET, "127.0.0.1", &trolladdr.sin_addr);

bind(localsockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
bind(globalsockfd, (struct sockaddr *)&globaladdr, sizeof(globaladdr));

fd_set rset;
FD_ZERO(&rset);
int maxfd1;
int len = sizeof(cliaddr);
int receivedbytes;
char buffer[1000] = {0x0};
struct message msg;
openlog(NULL, LOG_PID, LOG_USER);
int filesize = 0;
}

后来程序我正在做这样的recvfrom():

receivedbytes = recvfrom(localsockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&cliaddr, &len);

如果我想在收到后显示校验和,我应该怎么做?

1 个答案:

答案 0 :(得分:2)

你做不到。 (不是直接至少。)你也在谈论127.0.0.1:很可能永远不会计算UDP校验和(因为数据包不会进入线路,因此不会被破坏)。

选项:

  1. 使用SOCK_RAW套接字接收:这将保留接收缓冲区中的UDP标头。如上所述,如果您通过环回接口进行通话,则可能不会有UDP校验和,并且必须自己处理UDP校验和验证。

  2. 自己计算校验和。如果校验和失败(因为内核会拒绝它),你将不会在你的程序中收到数据报,并且你拥有了计算它所需的一切,所以你可以在接收器中自己重建它。 / p>

  3. 我不完全清楚为什么你需要UDP校验和。它不能保证在那里,并不是一个特别强大的完整性检查?