什么情况狂下,发送端的send函数成功, 但发送端抓不到对应的网络包? 这是一个很有趣的问题。
我们看下服务端程序:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
int main()
{
int sockSrv = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_addr.s_addr = INADDR_ANY;
addrSrv.sin_port = htons(8765);
bind(sockSrv, (const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));
listen(sockSrv, 5);
struct sockaddr_in addrClient;
int len = sizeof(struct sockaddr_in);
int sockConn = accept(sockSrv, (struct sockaddr *)&addrClient, (socklen_t*)&len);
while(1)
{
getchar();
char szRecvBuf[1001] = {0};
int iRet = recv(sockConn, szRecvBuf, sizeof(szRecvBuf) - 1, 0);
printf("iRet is %d\n", iRet);
}
getchar();
close(sockConn);
close(sockSrv);
return 0;
}
再看客户端程序:
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
int main()
{
int sockClient = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrSrv;
addrSrv.sin_addr.s_addr = inet_addr("10.100.70.140");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8765);
connect(sockClient, ( const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));
#define N 2000
char szSendBuf[N] = {0};
for(unsigned int i = 0; i < N; i++) //×Ö·ûÊý×é×îºóÒ»¸ö×Ö·û²»ÒªÇóÊÇ¡®\0¡¯
{
szSendBuf[i] = 'a';
}
int total = 0;
while(1)
{
int iRet = send(sockClient, szSendBuf, sizeof(szSendBuf) , 0);
total += iRet;
printf("iRet is %d, total send is %d\n", iRet, total);
getchar();
}
close(sockClient);
return 0;
}
启动服务端, 再启动客户端, 让服务端一直发发发, 发发发, 服务端不recv, 那么过不了多久, 服务端的内核缓冲区就会满了, 继续发的话, 数据就会在客户端的内核缓冲区中不断堆积, 此时send函数还是会成功的(因为客户端的发送缓冲区没有满), 但是, 此时tcpdump是抓不到包的? 为什么, 因为根本么有发送数据在网卡上流动。
这里, 我们要再次说说send函数, send函数并没有发送数据的能力, send函数的作用仅仅是把应用程序的数据拷贝到发送端的内核缓冲区中, 只要有足够的空间, send函数就不会阻塞, 就会返回成功。 至于内核缓冲区中的数据是否发送, 什么时候发送, 那是协议栈的事情, 跟send函数没有半毛钱的关系。
所以, send函数应该改名为copy_date_from_user_space_2_kerner_space.
好的, 不多说。 有兴趣的朋友, 可以亲自试下上述实验。