实现双机通信的C语言代码
的有关信息介绍如下:代码要求是什么? 基本实现 ping 的功能?
ping 代码
#include
#include
#define IP_RECORD_ROUTE 0x7
#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)
#define DEF_PACKET_SIZE 32 // Default packet size
#define MAX_PACKET 60000 // Max ICMP packet size 1024
#define MAX_IP_HDR_SIZE 60 // Max IP header size w/options
typedef struct _iphdr
{
unsigned int h_len:4; // Length of the header
unsigned int version:4; // Version of IP
unsigned char tos; // Type of service
unsigned short total_len; // Total length of the packet
unsigned short ident; // Unique identifier
unsigned short frag_and_flags; // Flags
unsigned char ttl; // Time to live
unsigned char proto; // Protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum
unsigned int sourceIP;
unsigned int destIP;
} IpHeader;
//
// ICMP header structure
//
typedef struct _icmphdr
{
BYTE i_type;
BYTE i_code; // Type sub code
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
// This is not the standard header, but we reserve space for time
ULONG timestamp;
} IcmpHeader;
//
// IP option header - use with socket option IP_OPTIONS
//
typedef struct _ipoptionhdr
{
unsigned char code; // Option type
unsigned char len; // Length of option hdr
unsigned char ptr; // Offset into options
unsigned long addr; // List of IP addrs
} IpOptionHeader;
//
// Function: FillICMPData
//
// Description:
// Helper function to fill in various fields for our ICMP request
//
void FillICMPData(char *icmp_data, int datasize)
{
IcmpHeader *icmp_hdr = NULL;
char *datapart = NULL;
icmp_hdr = (IcmpHeader*)(icmp_data); //+sizeof(IpHeader)
icmp_hdr->i_type = ICMP_ECHO; // Request an ICMP echo
icmp_hdr->i_code = 0;
icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
icmp_hdr->i_cksum = 0;
icmp_hdr->i_seq = 0;
datapart = icmp_data + sizeof(IcmpHeader);
//
// Place some junk in the buffer
//
memset(datapart,'E', datasize - sizeof(IcmpHeader));
}
//---------------------------------------------------------------------------
USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
//---------------------------------------------------------------------------
void DecodeIPOptions(char *buf, int bytes, void CALLBACK (*pDis)(const char* szMes))
{
IpOptionHeader *ipopt = NULL;
IN_ADDR inaddr;
int i;
HOSTENT *host = NULL;
char szMesBuffer;
ipopt = (IpOptionHeader *)(buf + 20);
if (pDis != NULL)
{
pDis("RR: ");
}
for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
{
inaddr.S_un.S_addr = ipopt->addr[i];
if (i != 0)
{
if (pDis != NULL)
{
pDis(" ");
}
}
host = gethostbyaddr((char *)&inaddr.S_un.S_addr, sizeof(inaddr.S_un.S_addr), AF_INET);
if (host)
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s) %s", inet_ntoa(inaddr), host->h_name);
pDis(szMesBuffer);
}
}
else
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s)", inet_ntoa(inaddr));
pDis(szMesBuffer);
}
}
}
return;
}
//---------------------------------------------------------------------------
int DecodeICMPHeader(char *buf, int bytes, struct sockaddr_in *from, void CALLBACK (*pDis)(const char* szMes))
{
IpHeader *iphdr = NULL;
IcmpHeader *icmphdr = NULL;
unsigned short iphdrlen;
DWORD tick;
static int icmpcount = 0;
char szMesBuffer;
char szMesBuffer1;
iphdr = (IpHeader *)buf;
// Number of 32-bit words * 4 = bytes
iphdrlen = iphdr->h_len * 4;
tick = GetTickCount();
if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
DecodeIPOptions(buf, bytes, pDis);
if (bytes < iphdrlen + ICMP_MIN)
{
//printf("Too few bytes from %s\n", inet_ntoa(from->sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Too few bytes from %s", inet_ntoa(from->sin_addr));
pDis(szMesBuffer);
}
}
icmphdr = (IcmpHeader*)(buf + iphdrlen);
if (icmphdr->i_type != ICMP_ECHOREPLY)
{
//printf("nonecho type %d recvd\n", icmphdr->i_type);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "nonecho type %d recvd", icmphdr->i_type);
pDis(szMesBuffer);
}
return -1;
}
// Make sure this is an ICMP reply to something we sent!
//
if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
{
//printf("someone else's packet!\n");
if (pDis != NULL)
{
pDis("someone else's packet!");
}
return -1;
}
//printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
//printf(" icmp_seq = %d. ", icmphdr->i_seq);
//printf(" time: %d ms", tick - icmphdr->timestamp);
//printf("\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
wsprintf(szMesBuffer1, " icmp_seq = %d. ", icmphdr->i_seq);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " time: %d ms", tick - icmphdr->timestamp);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " TTL = %d", iphdr->ttl);
lstrcat(szMesBuffer, szMesBuffer1);
pDis(szMesBuffer);
}
icmpcount++;
return tick - icmphdr->timestamp;
}
//---------------------------------------------------------------------------
ping(const char* szTargetAddress, int iDataSize, int iTimeOut, int iTimes, bool bReply, void CALLBACK (*pDis)(const char* szMes))
{
WSADATA wsaData;
SOCKET sockRaw = INVALID_SOCKET;
struct sockaddr_in dest,
from;
int bread,
fromlen = sizeof(from),
timeout = iTimeOut,
ret;
char *icmp_data = NULL,
*recvbuf = NULL;
unsigned int addr = 0;
USHORT seq_no = 0;
struct hostent *hp = NULL;
IpHeader ip_header;
IpOptionHeader ipopt;
char szMesBuffer;
if (timeout > 3000)
timeout = 3000;
else if (timeout < 100)
timeout = 100;
if (pDis != NULL)
{
wsprintf(szMesBuffer, "ping %s with %d bytes of data:", szTargetAddress, iDataSize);
pDis(szMesBuffer);
}
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
//printf("WSAStartup() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSAStartup() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}
sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sockRaw == INVALID_SOCKET)
{
//printf("WSASocket() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSASocket() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
// Set the send/recv timeout values
//
bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
if(bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_RCVTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_RCVTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_SNDTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_SNDTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
memset(&dest, 0, sizeof(dest));
//
// Resolve the endpoint's name if necessary
//
dest.sin_family = AF_INET;
if ((dest.sin_addr.s_addr = inet_addr(szTargetAddress)) == INADDR_NONE)
{
if ((hp = gethostbyname(szTargetAddress)) != NULL)
{
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
//printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "dest.sin_addr = %s", inet_ntoa(dest.sin_addr));
pDis(szMesBuffer);
}
}
else
{
//printf("gethostbyname() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "gethostbyname() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
}
//
// Create the ICMP packet
//
int datasize = iDataSize;
if (datasize < 0)
datasize = DEF_PACKET_SIZE;
datasize += sizeof(IcmpHeader);
if (datasize > MAX_PACKET)
datasize = MAX_PACKET;
icmp_data = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
recvbuf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
if (!icmp_data)
{
//printf("HeapAlloc() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "HeapAlloc() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}
//memset(icmp_data, 0, datasize); //, MAX_PACKET
FillICMPData(icmp_data, datasize);
//
// Start sending/receiving ICMP packets
//
int nCount = 0;
int iReceiveCount = 0;
if (iTimes < 2)
{
iTimes = 2;
}
while(1)
{
int bwrote;
if (nCount++ == iTimes)
break;
((IcmpHeader*)icmp_data)->i_cksum = 0;
((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
((IcmpHeader*)icmp_data)->i_seq = seq_no++;
((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize);
bwrote = sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));
if (bwrote == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("sendto() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "sendto() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
if (bwrote < datasize)
{
//printf("Wrote %d bytes\n", bwrote);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Wrote %d bytes", bwrote);
pDis(szMesBuffer);
}
}
bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr*)&from, &fromlen);
if (bread == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("recvfrom() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "recvfrom() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
DecodeICMPHeader(recvbuf, bread, &from, pDis); //return replay time ms
iReceiveCount++;
Sleep(50);//1000
}
// Cleanup
//
if (sockRaw != INVALID_SOCKET)
closesocket(sockRaw);
HeapFree(GetProcessHeap(), 0, recvbuf);
HeapFree(GetProcessHeap(), 0, icmp_data);
WSACleanup();
if (pDis != NULL && bReply)
{
pDis(" ");
nCount--;
wsprintf(szMesBuffer, "Packets: Sent = %d, Received = %d, Lost = %d (%d%s", nCount, iReceiveCount, nCount - iReceiveCount, (nCount - iReceiveCount) * 100 / nCount, "% loss)");
pDis(szMesBuffer);
pDis(" ");
}
return 0;
}
//---------------------------------------------------------------------------
调用方法:
ping(
szTargetAddress, //目标地址 //IP 或网址
iDataSize, //数据包大小
iTimeOut, //延时
iTimes, //发送次数
bReply, //是否显示信息
CALLBACK (*pDis)(const char* szMes)//显示信息的函数指针
);
void pingMessage(const char* szMes);
main()
{
ping("127.0.0.1", 32, 500, 5, true, pingMessage);
}
void pingMessage(const char* szMes)
{
printf("%s\n", szMes);
}
你下载linux内核代码就可以了。