用原始套接字获得IP头的问题
发送端程序调用sendto()返回52,即IP头20Bytes, UDP头8Bytes,Data24Bytes,共发送52Bytes的包
为什么以下收包程序只收到24Bytes,未收到IP头阿? 请指教,谢谢
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h> // IP_HDRINCL
#pragma comment(lib, "ws2_32.lib")
/*========================Function: main()==========================
Description:
Main thread of execution. Initialize Winsock, create a
socket, bind it to a local interface and port, and then
read datagrams.
====================================================================*/
int main()
{
WSADATA wsd; //存储所加载版本信息
SOCKET RecvSock; //与本地地址结构bind
SOCKADDR_IN LocalAddr, //本地地址结构
SendAddr; //发送方地址结构
int ret; //bytes which has been received
int iOpt;
FILE* fp;
int SendLen; //size of SendAddr
char RecvBuff[4096]; //Buffer to receive data
// Load the corresponding version of Winsock DLL
if(WSAStartup(MAKEWORD(2,2), &wsd)!=0)
{
printf("Failed to load Winsock!\n");
return 1;
}
// Create socket
RecvSock=socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if(RecvSock==INVALID_SOCKET)
{
printf("socket() failed: %d\n", WSAGetLastError());
return 1;
}
// Enable the header include option to operate the UDP header
iOpt=TRUE;
ret=setsockopt(RecvSock, IPPROTO_IP, IP_HDRINCL, (char*)&iOpt, sizeof(iOpt));
if(ret==SOCKET_ERROR)
{
printf("setsockopt(IP_HDRINCL) failed: %d\n", WSAGetLastError());
return -1;
}
// Resolve the recipient's IP address
LocalAddr.sin_family=AF_INET;
LocalAddr.sin_addr.s_addr=inet_addr("192.168.58.103");
LocalAddr.sin_port=htons(5150);
// Bind the socket to the local interface and port
if( bind(RecvSock, (SOCKADDR*)&LocalAddr, sizeof(LocalAddr)) == SOCKET_ERROR )
{
printf("bind() failed: %d\n", WSAGetLastError());
return 1;
}
// Receive datagrams
SendLen=sizeof(SendAddr);
//接收数据的缓冲区清空
memset(RecvBuff, 0, sizeof(RecvBuff));
ret=recvfrom(RecvSock, RecvBuff, 4096, 0, (SOCKADDR*)&SendAddr, &SendLen);
// OutPut the result
// RecvBuff[ret]='\0';
fp=fopen("receive.txt","wb");
if(fwrite(RecvBuff, 1, 4096, fp)==0)
{
printf("Failed to write receive.txt!\n");
return 1;
}
printf("Received: %d bytes from client: %s:%d\n", ret, inet_ntoa(SendAddr.sin_addr), ntohs(SendAddr.sin_port));
//close
closesocket(RecvSock);
WSACleanup();
return 0;
}