當前位置:首頁 » 操作系統 » cping源碼

cping源碼

發布時間: 2022-06-20 16:08:00

❶ 用C#寫一個類似cmd的控制台程序,實現ping的功能!!!(求完整程序源代碼!)

using System;
using System.Net;
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
int count = 4;
IPAddress addr = IPAddress.Parse("220.181.111.86");
Ping ping = new Ping();
long timeSum = 0;
int succCount = 0;
//發送
Console.WriteLine("正在ping {0}", addr);
for (int i = 0; i < count; ++i)
{
PingReply pr = ping.Send(addr);
if (pr.Status == IPStatus.TimedOut)
Console.WriteLine("超時");
else if (pr.Status == IPStatus.Success)
{
Console.WriteLine("延時:{0}毫秒", pr.RoundtripTime);
++succCount;
timeSum += pr.RoundtripTime;
}
}
if (timeSum != 0)
Console.WriteLine("平均延時{0}毫秒,丟包率{1}%", 1.0 * timeSum / succCount, (count - succCount) * 100.0 / count);
else
Console.WriteLine("丟包率100%");
return;
}
}

❷ 判斷網路連接是否成功源碼分享,一看就懂

以安卓為例:

利用Android自帶的ConnectivityManager類。

有時候連上了wifi,但這個wifi是上不了網的,可以通過ping 網路網址來判斷是否可以上網。

也可以利用get請求訪問網路,如果get請求成功,說明可以上網。

判斷網路是否已經連接

//checkallnetworkconnect,WIFIormobile
(finalContextcontext){
booleanhasWifoCon=false;
booleanhasMobileCon=false;

ConnectivityManagercm=(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo[]netInfos=cm.getAllNetworkInfo();
for(NetworkInfonet:netInfos){

Stringtype=net.getTypeName();
if(type.equalsIgnoreCase("WIFI")){
LevelLogUtils.getInstance().i(tag,"getWificonnection");
if(net.isConnected()){
hasWifoCon=true;
}
}

if(type.equalsIgnoreCase("MOBILE")){
LevelLogUtils.getInstance().i(tag,"getMobileconnection");
if(net.isConnected()){
hasMobileCon=true;
}
}
}
returnhasWifoCon||hasMobileCon;

}

利用 ping 判斷 Internet 能夠 請求成功

//
(finalContextcontext){
Runtimeruntime=Runtime.getRuntime();
try{
ProcesspingProcess=runtime.exec("/system/bin/ping-c1www..com");
intexitCode=pingProcess.waitFor();
return(exitCode==0);
}catch(Exceptione){
e.printStackTrace();
}
returnfalse;
}

編程高手看

下面是ping的源碼,你把main函數改成一般函數,把printf函數的輸出改為到圖形化界面的輸出就可以了,正好也鍛煉一下你
:)

// Mole Name: Ping.c
//
// Description:
// This sample illustrates how an ICMP ping app can be written
// using the SOCK_RAW socket type and IPPROTO_ICMP protocol.
// By creating a raw socket, the underlying layer does not change
// the protocol header so that when we submit the ICMP header
// nothing is changed so that the receiving end will see an
// ICMP packet. Additionally, we use the record route IP option
// to get a round trip path to the endpoint. Note that the size
// of the IP option header that records the route is limited to
// nine IP addresses.
//
// Compile:
// cl -o Ping Ping.c ws2_32.lib /Zp1
//
// Command Line Options/Parameters:
// Ping [host] [packet-size]
//
// host String name of host to ping
// packet-size Integer size of packet to send
// (smaller than 1024 bytes)
//
//#pragma pack(1)

#define WIN32_LEAN_AND_MEAN
#include
#include
#include
#include

#define IP_RECORD_ROUTE 0x7
//
// IP header structure
//
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;
#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 // Minimum 8-byte ICMP packet (header)

//
// 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[9]; // List of IP addrs
} IpOptionHeader;

#define DEF_PACKET_SIZE 32 // Default packet size
#define MAX_PACKET 1024 // Max ICMP packet size
#define MAX_IP_HDR_SIZE 60 // Max IP header size w/options

BOOL bRecordRoute;
int datasize;
char *lpdest;

//
// Function: usage
//
// Description:
// Print usage information
//
void usage(char *progname)
{
printf("usage: ping -r [data size]\n");
printf(" -r record route\n");
printf(" host remote machine to ping\n");
printf(" datasize can be up to 1KB\n");
ExitProcess(-1);

//
// 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;
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));
}

//
// Function: checksum
//
// Description:
// This function calculates the 16-bit one's complement sum
// of the supplied buffer (ICMP) header
//
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);
//
// Function: DecodeIPOptions
//
// Description:
// If the IP option header is present, find the IP options
// within the IP header and print the record route option
// values
//
void DecodeIPOptions(char *buf, int bytes)
{
IpOptionHeader *ipopt = NULL;
IN_ADDR inaddr;
int i;
HOSTENT *host = NULL;

ipopt = (IpOptionHeader *)(buf + 20);

printf("RR: ");
for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
{
inaddr.S_un.S_addr = ipopt->addr[i];
if (i != 0)
printf(" ");
host = gethostbyaddr((char *)&inaddr.S_un.S_addr,
sizeof(inaddr.S_un.S_addr), AF_INET);
if (host)
printf("(%-15s) %s\n", inet_ntoa(inaddr), host->h_name);
else
printf("(%-15s)\n", inet_ntoa(inaddr));
}
return;
}

//
// Function: DecodeICMPHeader
//
// Description:
// The response is an IP packet. We must decode the IP header to
// locate the ICMP data.
//
void DecodeICMPHeader(char *buf, int bytes,
struct sockaddr_in *from)
{
IpHeader *iphdr = NULL;
IcmpHeader *icmphdr = NULL;
unsigned short iphdrlen;
DWORD tick;
static int icmpcount = 0;

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);

if (bytes < iphdrlen + ICMP_MIN)
{
printf("Too few bytes from %s\n",
inet_ntoa(from->sin_addr));
}
icmphdr = (IcmpHeader*)(buf + iphdrlen);

if (icmphdr->i_type != ICMP_ECHOREPLY)
{
printf("nonecho type %d recvd\n", icmphdr->i_type);
return;
}
// Make sure this is an ICMP reply to something we sent!
//
if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
{
printf("someone else's packet!\n");
return ;
}
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");

icmpcount++;
return;
}

void ValidateArgs(int argc, char **argv)
{
int i;

bRecordRoute = FALSE;
lpdest = NULL;
datasize = DEF_PACKET_SIZE;

for(i = 1; i < argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 'r': // Record route option
bRecordRoute = TRUE;
break;
default:
usage(argv[0]);
break;
}
}
else if (isdigit(argv[i][0]))
datasize = atoi(argv[i]);
else
lpdest = argv[i];
}
}
//
// Function: main
//
// Description:
// Setup the ICMP raw socket, and create the ICMP header. Add
// the appropriate IP option header, and start sending ICMP
// echo requests to the endpoint. For each send and receive,
// we set a timeout value so that we don't wait forever for a
// response in case the endpoint is not responding. When we
// receive a packet decode it.
//
int main(int argc, char **argv)
{

WSADATA wsaData;
SOCKET sockRaw = INVALID_SOCKET;
struct sockaddr_in dest,
from;
int bread,
fromlen = sizeof(from),
timeout = 1000,
ret;
char *icmp_data = NULL,
*recvbuf = NULL;
unsigned int addr = 0;
USHORT seq_no = 0;
struct hostent *hp = NULL;
IpOptionHeader ipopt;

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("WSAStartup() failed: %d\n", GetLastError());
return -1;
}
ValidateArgs(argc, argv);

//
// WSA_FLAG_OVERLAPPED flag is required for SO_RCVTIMEO,
// SO_SNDTIMEO option. If NULL is used as last param for
// WSASocket, all I/O on the socket is synchronous, the
// internal user mode wait code never gets a chance to
// execute, and therefore kernel-mode I/O blocks forever.
// A socket created via the socket function has the over-
// lapped I/O attribute set internally. But here we need
// to use WSASocket to specify a raw socket.
//
// If you want to use timeout with a synchronous
// nonoverlapped socket created by WSASocket with last
// param set to NULL, you can set the timeout by using
// the select function, or you can use WSAEventSelect and
// set the timeout in the WSAWaitForMultipleEvents
// function.
//
sockRaw = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (sockRaw == INVALID_SOCKET)
{
printf("WSASocket() failed: %d\n", WSAGetLastError());
return -1;
}
if (bRecordRoute)
{
// Setup the IP option header to go out on every ICMP packet
//
ZeroMemory(&ipopt, sizeof(ipopt));
ipopt.code = IP_RECORD_ROUTE; // Record route option
ipopt.ptr = 4; // Point to the first addr offset
ipopt.len = 39; // Length of option header

ret = setsockopt(sockRaw, IPPROTO_IP, IP_OPTIONS,
(char *)&ipopt, sizeof(ipopt));
if (ret == SOCKET_ERROR)
{
printf("setsockopt(IP_OPTIONS) failed: %d\n",
WSAGetLastError());
}
}
// 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());
return -1;
}
timeout = 1000;
bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO,
(char*)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
printf("setsockopt(SO_SNDTIMEO) failed: %d\n",
WSAGetLastError());
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(lpdest)) == INADDR_NONE)
{
if ((hp = gethostbyname(lpdest)) != 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));
}
else
{
printf("gethostbyname() failed: %d\n",
WSAGetLastError());
return -1;
}
}
//
// Create the ICMP packet
//
datasize += sizeof(IcmpHeader);

icmp_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
MAX_PACKET);
recvbuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
MAX_PACKET);
if (!icmp_data)
{
printf("HeapAlloc() failed: %d\n", GetLastError());
return -1;
}
memset(icmp_data,0,MAX_PACKET);
FillICMPData(icmp_data,datasize);
//
// Start sending/receiving ICMP packets
//
while(1)
{
static int nCount = 0;
int bwrote;

if (nCount++ == 4)
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");
continue;
}
printf("sendto() failed: %d\n", WSAGetLastError());
return -1;
}
if (bwrote < datasize)
{
printf("Wrote %d bytes\n", bwrote);
}
bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0,
(struct sockaddr*)&from, &fromlen);
if (bread == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
printf("timed out\n");
continue;
}
printf("recvfrom() failed: %d\n", WSAGetLastError());
return -1;
}
DecodeICMPHeader(recvbuf, bread, &from);

Sleep(1000);
}
// Cleanup
//
if (sockRaw != INVALID_SOCKET)
closesocket(sockRaw);
HeapFree(GetProcessHeap(), 0, recvbuf);
HeapFree(GetProcessHeap(), 0, icmp_data);

WSACleanup();
return 0;
}

❹ 求windows下ping程序c源代碼,模擬的ping也行,能編譯通過就行,網上很多通不過

#pragma pack(4)
#define WIN32_LEAN_AND_MEAN
#include
#include
#include
#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)
/* The IP header */
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;
unsigned char proto; // protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum
unsigned int sourceIP;
unsigned int destIP;
}IpHeader;
//
// ICMP header
//
typedef struct _ihdr {
BYTE i_type;
BYTE i_code; /* type sub code */
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
/* This is not the std header, but we reserve space for time */
ULONG timestamp;
}IcmpHeader;
#define STATUS_FAILED 0xFFFF
#define DEF_PACKET_SIZE 32
#define MAX_PACKET 1024
#define xmalloc(s) HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(s))
#define xfree(p) HeapFree (GetProcessHeap(),0,(p))
void fill_icmp_data(char *, int);
USHORT checksum(USHORT *, int);
void decode_resp(char *,int ,struct sockaddr_in *);
void Usage(char *progname){
fprintf(stderr,"Usage: ");
fprintf(stderr,"%s [data_size] ",progname);
fprintf(stderr,"datasize can be up to 1Kb ");
ExitProcess(STATUS_FAILED);
}
int main(int argc, char **argv){
WSADATA wsaData;
SOCKET sockRaw;
struct sockaddr_in dest,from;
struct hostent * hp;
int bread,datasize;
int fromlen = sizeof(from);
int timeout = 1000;
char *dest_ip;
char *icmp_data;
char *recvbuf;
unsigned int addr=0;
USHORT seq_no = 0;
if (WSAStartup(MAKEWORD(2,1),&wsaData) != 0){
fprintf(stderr,"WSAStartup failed: %d ",GetLastError());
ExitProcess(STATUS_FAILED);
}
if (argc <2 ) {
Usage(argv[0]);
}
sockRaw = WSASocket (AF_INET,
SOCK_RAW,
IPPROTO_ICMP,
NULL, 0,0);
if (sockRaw == INVALID_SOCKET) {
fprintf(stderr,"WSASocket() failed: %d ",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
bread = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,
sizeof(timeout));
if(bread == SOCKET_ERROR) {
fprintf(stderr,"failed to set recv timeout: %d ",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
timeout = 1000;
bread = setsockopt(sockRaw,SOL_SOCKET,SO_SNDTIMEO,(char*)&timeout,
sizeof(timeout));
if(bread == SOCKET_ERROR) {
fprintf(stderr,"failed to set send timeout: %d ",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
memset(&dest,0,sizeof(dest));
hp = gethostbyname(argv[1]);
if (!hp){
addr = inet_addr(argv[1]);
}
if ((!hp) && (addr == INADDR_NONE) ) {
fprintf(stderr,"Unable to resolve %s ",argv[1]);
ExitProcess(STATUS_FAILED);
}
if (hp != NULL)
memcpy(&(dest.sin_addr),hp->h_addr,hp->h_length);
else
dest.sin_addr.s_addr = addr;
if (hp)
dest.sin_family = hp->h_addrtype;
else
dest.sin_family = AF_INET;
dest_ip = inet_ntoa(dest.sin_addr);
if (argc >2) {
datasize = atoi(argv[2]);
if (datasize == 0)
datasize = DEF_PACKET_SIZE;
}
else
datasize = DEF_PACKET_SIZE;
datasize += sizeof(IcmpHeader);
icmp_data = xmalloc(MAX_PACKET);
recvbuf = xmalloc(MAX_PACKET);
if (!icmp_data) {
fprintf(stderr,"HeapAlloc failed %d ",GetLastError());
ExitProcess(STATUS_FAILED);
}
memset(icmp_data,0,MAX_PACKET);
fill_icmp_data(icmp_data,datasize);
while(1) {
int bwrote;
((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 ");
continue;
}
fprintf(stderr,"sendto failed: %d ",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
if (bwrote < datasize ) {
fprintf(stdout,"Wrote %d bytes ",bwrote);
}
bread = recvfrom(sockRaw,recvbuf,MAX_PACKET,0,(struct sockaddr*)&from,
&fromlen);
if (bread == SOCKET_ERROR){
if (WSAGetLastError() == WSAETIMEDOUT) {
printf("timed out ");
continue;
}
fprintf(stderr,"recvfrom failed: %d ",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
decode_resp(recvbuf,bread,&from);
Sleep(1000);
}
return 0;
}
/*
The response is an IP packet. We must decode the IP header to locate
the ICMP data
*/
void decode_resp(char *buf, int bytes,struct sockaddr_in *from) {
IpHeader *iphdr;
IcmpHeader *icmphdr;
unsigned short iphdrlen;
iphdr = (IpHeader *)buf;
iphdrlen = iphdr->h_len * 4 ; // number of 32-bit words *4 = bytes
if (bytes < iphdrlen + ICMP_MIN) {
printf("Too few bytes from %s ",inet_ntoa(from->sin_addr));
}
icmphdr = (IcmpHeader*)(buf + iphdrlen);
if (icmphdr->i_type != ICMP_ECHOREPLY) {
fprintf(stderr,"non-echo type %d recvd ",icmphdr->i_type);
return;
}
if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) {
fprintf(stderr,"someone else's packet! ");
return ;
}
printf("%d bytes from %s:",bytes, inet_ntoa(from->sin_addr));
printf(" icmp_seq = %d. ",icmphdr->i_seq);
printf(" time: %d ms ",GetTickCount()-icmphdr->timestamp);
printf(" ");
}
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);
}
/*
Helper function to fill in various stuff in our ICMP request.
*/
void fill_icmp_data(char * icmp_data, int datasize){
IcmpHeader *icmp_hdr;
char *datapart;
icmp_hdr = (IcmpHeader*)icmp_data;
icmp_hdr->i_type = 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));
}

估計你也試過,網上搜到的。

❺ C#源代碼。數據包互ping 相互ping包

C#是一種安全的、穩定的、簡單的、優雅的,由C和C++衍生出來的面向對象的編程語言。它在繼承C和C++強大功能的同時去掉了一些它們的復雜特性(例如沒有宏和模版,不允許多重繼承)。

❻ 易語言 埠ping顯延遲 持續ping 源碼 如圖

這個實現應該不難 (我沒做過)
就是請求訪問網站,然後有個等待時間,那個就是ping
你也可以試一下系統自帶cmd 輸入:ping www..com回車
然後會顯示一些信息 包括延遲
實時顯示有點難度 畢竟請求訪問時本身就存在著延遲
易語言的話你可以用一個時鍾
時鍾裡面的代碼大概就是如同CMD一樣ping你輸入的網站,然後返回延遲的時間,就是你想要的ping值
(不太懂這方面,有說錯的地方見諒)

❼ 這個易語言ping源碼 誰能給下 謝謝啦 就是把IP地址輸入 下面返回 PING的值。 代碼不知道怎麼寫。

.版本 2
.如果 (編輯框1.內容 ≠ 「」)
運行 (「cmd /c ping 」 + 編輯框1.內容 + 「-t」 + 「 >c:\ping.txt」, 真, #隱藏窗口)
編輯框2.內容 = 到文本 (讀入文件 (「c:\ping.txt」))
刪除文件 (「c:\ping.txt」)
.否則
.如果結束
是用CMD的保存文件。讀取CMD的保存文件。原理就是這樣

❽ 求源碼:1,PING程序2,ftp程序3,區域網截包程序

這個你得花錢

❾ 請教如何用C語言實現ping命令

如果你想獲取到Ping的結果
那麼直接system 調用ping或者popen調用即可。
如果想自己實現,就需要用socket自行發Ping包,並獲取回應
這個就很麻煩了。 建議可以看一下gnu ping的源碼,或者busybox的ping部分代碼。

❿ 代碼編程——ping命令流程(圖)

不是我寫的,找的。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define WIN32_LEAN_AND_MEAN
#include <winsock.h>
#pragma comment(lib, "Wsock32.lib")

#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0

//#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)
#define ICMP_MIN (8 + 4) // minimum 8 byte icmp packet (just header + timestamp)

// IP header
typedef struct _tagX_iphdr
{
unsigned char h_len:4; // length of the header
unsigned char 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; // ttl
unsigned char proto; // protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum

unsigned int sourceIP;
unsigned int destIP;
}XIpHeader;

// ICMP header
typedef struct _tagX_icmphdr
{
unsigned char i_type;
unsigned char i_code;
unsigned short i_cksum;
unsigned short i_id;
unsigned short i_seq;
unsigned long i_timestamp;
}XIcmpHeader;

//puclic code
//網際校驗和生產演算法
//網際校驗和是被校驗數據16位值的反碼和(ones-complement sum)
unsigned short in_cksum(unsigned short* addr, int len)
{
int nleft = len;
int sum = 0;
unsigned short* w = addr;
unsigned short answer = 0;

while(nleft > 1) {
sum += *w++;
nleft -= 2;
}

if(nleft == 1) {
*(unsigned char*)(&answer) = *(unsigned char*)w;
sum += answer;
}

sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;

return (answer);
}

void fill_IcmpData(char *buf, int datasize)
{
if (buf)
{
char ch = 0;
char* icmpdata = buf + sizeof(XIcmpHeader);
fprintf(stdout, "(IcmpData)\r\n");
for (int i = 0; i < datasize; i++)
{
ch = 'A' + i%('z' - 'A');
*(icmpdata + i) = ch;
fprintf(stdout, "%c", ch);
}
fprintf(stdout, "\r\n");
}
}

void fill_IcmpHeader(char *buf, int datasize)
{
static unsigned short seq_no = 0;
XIcmpHeader *icmp_hdr = (XIcmpHeader *)buf;
if (icmp_hdr)
{
icmp_hdr->i_type = ICMP_ECHO;
icmp_hdr->i_code = 0;
icmp_hdr->i_cksum = 0;

icmp_hdr->i_id = (unsigned short)GetCurrentProcessId();

icmp_hdr->i_seq = seq_no++;

icmp_hdr->i_timestamp = (unsigned long)::GetTickCount();

icmp_hdr->i_cksum = in_cksum((unsigned short*)buf, sizeof(XIcmpHeader) + datasize);

fprintf(stdout, "(IcmpHeader)\r\n");
fprintf(stdout, "%02X%02X%04X\r\n", icmp_hdr->i_type, icmp_hdr->i_code, icmp_hdr->i_cksum);
fprintf(stdout, "%04X%04X\r\n", icmp_hdr->i_id, icmp_hdr->i_seq);
fprintf(stdout, "%08X\r\n", icmp_hdr->i_timestamp);
}
}

// decode
void decode_IpIcmp(char *buf, int size)
{
XIpHeader *ip_hdr = (XIpHeader *)buf;
unsigned short iphdrlen;
if (ip_hdr)
{
fprintf(stdout, "(IpHeader)\r\n");
fprintf(stdout, "%01X%01X%02X%04X\r\n", ip_hdr->version, ip_hdr->h_len, ip_hdr->tos, ip_hdr->total_len);
fprintf(stdout, "%04X%04X\r\n", ip_hdr->ident, ip_hdr->frag_and_flags);
fprintf(stdout, "%02X%02X%04X\r\n", ip_hdr->ttl, ip_hdr->proto, ip_hdr->checksum);

//iphdrlen = ip_hdr->h_len * 4; // number of 32-bit words *4 = bytes
iphdrlen = ip_hdr->h_len << 2; // number of 32-bit words *4 = bytes
fprintf(stdout, "(IcmpHeader)\r\n");
if (size < iphdrlen + ICMP_MIN)
{
fprintf(stdout, "Reply %d bytes Too few\r\n", size);
}
else
{
XIcmpHeader *icmp_hdr = (XIcmpHeader *)(buf + iphdrlen);

fprintf(stdout, "%02X%02X%04X\r\n", icmp_hdr->i_type, icmp_hdr->i_code, icmp_hdr->i_cksum);
fprintf(stdout, "%04X%04X\r\n", icmp_hdr->i_id, icmp_hdr->i_seq);
fprintf(stdout, "%08X\r\n", icmp_hdr->i_timestamp);

unsigned long timestamp = 0;

timestamp = (unsigned long)::GetTickCount();

timestamp -= icmp_hdr->i_timestamp;

struct sockaddr_in from;
from.sin_addr.s_addr = ip_hdr->sourceIP;

fprintf(stdout, "Reply %d bytes from: %s time<%d TTL=%d icmp_seq=%d\r\n",
size,
inet_ntoa(from.sin_addr),
timestamp,
ip_hdr->ttl,
icmp_hdr->i_seq
);
}
}
}

int main(int argc, char **argv)
{
int ret = 0;

WSADATA ws;
WSAStartup(0x0101,&ws);

int iIcmpDataSize = 0;
struct sockaddr_in dest,from;
unsigned int addr = 0;
struct hostent *hp;

char buffer[1024];
char recv_buffer[1024];

if(argc < 2)
{
fprintf(stderr, "Usage: %s [host|ip] [datasize]\r\n", argv[0]);
return 0;
}

if (argc > 2)
iIcmpDataSize = atoi(argv[2]);
if (iIcmpDataSize < 1 || iIcmpDataSize > 1024)
iIcmpDataSize = 10;

memset(&dest, 0, sizeof dest);
dest.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if (!hp)
addr = inet_addr(argv[1]);
if ((!hp) && (addr == INADDR_NONE))
{
fprintf(stderr,"Unable to resolve %s\r\n",argv[1]);
return 0;
}
if (hp != NULL)
memcpy(&(dest.sin_addr), hp->h_addr,hp->h_length);
else
dest.sin_addr.s_addr = addr;

int sockfd;
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

fprintf(stdout, "XPing...\r\n");
for (int i = 0; i < 3; i++)
{
fprintf(stdout, "Echo...\r\n");
memset(buffer, 0, 1024);
fill_IcmpData(buffer, iIcmpDataSize);
fill_IcmpHeader(buffer, iIcmpDataSize);
XIcmpHeader *icmp_hdr = (XIcmpHeader *)buffer;
int iSendSize = sendto(sockfd, buffer, sizeof(XIcmpHeader) + iIcmpDataSize, 0, (struct sockaddr*)&dest, sizeof(dest));

fprintf(stdout, "Reply...\r\n");
memset(&from, 0, sizeof from);
memset(recv_buffer, 0, 1024);

int fromlen = sizeof(from);
int iRecvSize = recvfrom(sockfd, recv_buffer, 1024, 0, (struct sockaddr*)&from, &fromlen);

if (iRecvSize > 0)
decode_IpIcmp(recv_buffer, iRecvSize);
}

WSACleanup();

return ret;
}

熱點內容
舊電腦共享伺服器 發布:2024-04-27 06:32:21 瀏覽:338
java程序練習 發布:2024-04-27 06:24:00 瀏覽:437
sql30 發布:2024-04-27 06:22:10 瀏覽:54
怎樣防止sql注入 發布:2024-04-27 06:11:25 瀏覽:235
安卓為什麼不能登蘋果系統的游戲 發布:2024-04-27 06:11:23 瀏覽:600
編程日課 發布:2024-04-27 05:56:54 瀏覽:619
漏洞上傳工具 發布:2024-04-27 05:50:58 瀏覽:716
手機如何選擇存儲 發布:2024-04-27 05:40:25 瀏覽:799
機架式伺服器怎麼操作 發布:2024-04-27 05:19:02 瀏覽:815
我的世界minez網易伺服器 發布:2024-04-27 05:09:26 瀏覽:384