『壹』 如何用c語言實現ping程序
頭文件 stdlib.h
函數 system()
傳入參數 字元串cmd命令
ping成功返回0 不成功返回1
『貳』 如何用C語言調用ping命令
C語言調用ping命令,參考代碼:
#include <windows.h>
#include <stdio.h>
#include <string.h>
char YN(int k) {
FILE *f;
char fn[40];
char ln[80];
char yn;
int n;
yn='N';
sprintf(fn,"d:\\ping%d.txt",k);
f=fopen(fn,"r");
if (NULL!=f) {
n=0;
while (1) {
if (NULL==fgets(ln,80,f)) break;//
if (strstr(ln,"ms ")) {
yn='Y';
break;//
}
n++;
if (n>=4) break;//
}
fclose(f);
}
return yn;
}
void main(int argc,char **argv) {
char cmdstr[256];
int i;
int IP[3];
char c;
if (argc<2) {
USAGE:
printf("Usage example:\n %s 192.168.60.\nto test 192.168.60.1-254\n",argv[0]);
return;
}
if (4==sscanf(argv[1],"%d.%d.%d%c",&IP[0],&IP[1],&IP[2],&c)) {
if (0<=IP[0] && IP[0]<=255
&& 0<=IP[1] && IP[1]<=255
&& 0<=IP[2] && IP[2]<=255
&& '.'==c) {
for (i=1;i<255;i++) {
sprintf(cmdstr,"cmd /c ping %s%d -n 1 -w 1000 >d:\\ping%d.txt",argv[1],i,i);
WinExec(cmdstr,SW_HIDE);
}
Sleep(3000);
for (i=1;i<255;i++) {
printf("%c %s%d\n",YN(i),argv[1],i);
}
Sleep(3000);
WinExec("cmd /c del /q d:\\ping*.txt",SW_HIDE);
} else goto USAGE;
} else goto USAGE;
}
『叄』 代碼編程——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;
}
『肆』 如何用C語言實現ping-a命令非常急。。知道的一定要告訴我啊。。
#include<stdio.h>
#include<windows.h>
main()
{
system("Ping -a");
}
『伍』 如何使用C語言來判斷ping命令是否能ping通,求代碼。 要c的不要c++或c#的。
代碼在 MAC OS 下運行良好,在 linux 下得話需要稍作修改
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
intmain(void)
{
charhost[256],cmd[256];
printf("pleaseinputdest_host:");
scanf("%s",host);
strncpy(cmd,"ping-c5",9);
strncat(cmd,host,strlen(host));
strncat(cmd,">ping.txt",11);
pid_tpid=fork();
if(pid<0)
{
printf("forkerror ");
exit(-1);
}
if(pid==0)
{
if(execlp("/bin/sh","sh","-c",cmd,(char*)0)<0)
printf("execlperror ");
exit(0);
}
if(waitpid(pid,NULL,0)<0)
printf("waitpiderror ");
intfd=open("ping.txt",O_RDWR);
intn;
charbuf[1024];
n=read(fd,buf,sizeof(buf));
if(n<=0)
{
printf("readerror ");
exit(-1);
}
if(strstr(buf,"100.0%")==NULL)
printf("canreach%s",host);
else
printf("can'treach%s",host);
close(fd);
return0;
}
如果你想要 ping 程序,剛好我最近寫了一個,要的話私信
『陸』 C語言與網路問題 高手進
ping命令是dos命令可以創建一個cmd進程,然後建立兩個管道用來得到結果 實現.
下面是一個網路編程的實例, Syn掃描器代碼,可以作為參考.
基本可以看為是 ping命令的實現
//getallIP.cpp
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
////////////////
// 初始化 Windows sockets API.
//
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData)) {
printf("WSAStartup failed %s\n", WSAGetLastError());
return 0;
}
//////////////////
// 獲得主機名.
//
char hostname[256];
int res = gethostname(hostname, sizeof(hostname));
if (res != 0) {
printf("Error: %u\n", WSAGetLastError());
return 0;
}
printf("hostname=%s\n", hostname);
////////////////
// 根據主機名獲取主機信息.
//
hostent* pHostent = gethostbyname(hostname);
if (pHostent==NULL) {
printf("Error: %u\n", WSAGetLastError());
return 0;
}
//////////////////
// 解析返回的hostent信息.
//
hostent& he = *pHostent;
printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
he.h_name, he.h_aliases, he.h_addrtype, he.h_length);
sockaddr_in sa;
//根據 he.h_addr_list[nAdapter]是否為空來獲取所有IP地址
for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
memcpy ( &sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
// 輸出機器的IP地址.
printf("Address [%d%]: %s\n",nAdapter, inet_ntoa(sa.sin_addr)); // 顯示地址串
}
//////////////////
// 終止 Windows sockets API
//
WSACleanup();
return 0;
}
//mstcpip.h
// Copyright (C) Microsoft Corporation, 1996-1999
#if _MSC_VER > 1000
#pragma once
#endif
/* Argument structure for SIO_KEEPALIVE_VALS */
struct tcp_keepalive {
u_long onoff;
u_long keepalivetime;
u_long keepaliveinterval;
};
// New WSAIoctl Options
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define SIO_RCVALL_MCAST _WSAIOW(IOC_VENDOR,2)
#define SIO_RCVALL_IGMPMCAST _WSAIOW(IOC_VENDOR,3)
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
#define SIO_ABSORB_RTRALERT _WSAIOW(IOC_VENDOR,5)
#define SIO_UCAST_IF _WSAIOW(IOC_VENDOR,6)
#define SIO_LIMIT_BROADCASTS _WSAIOW(IOC_VENDOR,7)
#define SIO_INDEX_BIND _WSAIOW(IOC_VENDOR,8)
#define SIO_INDEX_MCASTIF _WSAIOW(IOC_VENDOR,9)
#define SIO_INDEX_ADD_MCAST _WSAIOW(IOC_VENDOR,10)
#define SIO_INDEX_DEL_MCAST _WSAIOW(IOC_VENDOR,11)
//synscan.cpp
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <time.h>
#include "mstcpip.h"
#pragma comment(lib,"ws2_32.lib")
#define SEQ 0x28376839
SOCKET sockRaw = INVALID_SOCKET,
sockListen = INVALID_SOCKET;
struct sockaddr_in dest;
BOOL ScanOK=FALSE;
char *DEST_HOST;
int DEST_PORT;
int DEST_PORTEND;
int play=0;
clock_t start,end;//程序運行的起始和結束時間
float costtime;//程序耗時
typedef struct _iphdr
{
unsigned char h_lenver; //4位首部長度+4位IP版本號
unsigned char tos; //8位服務類型TOS
unsigned short total_len; //16位總長度(位元組)
unsigned short ident; //16位標識
unsigned short frag_and_flags; //3位標志位
unsigned char ttl; //8位生存時間 TTL
unsigned char proto; //8位協議 (TCP, UDP 或其他)
unsigned short checksum; //16位IP首部校驗和
unsigned int sourceIP; //32位源IP地址
unsigned int destIP; //32位目的IP地址
}IP_HEADER;
typedef struct _tcphdr //定義TCP首部
{
USHORT th_sport; //16位源埠
USHORT th_dport; //16位目的埠
unsigned int th_seq; //32位序列號
unsigned int th_ack; //32位確認號
unsigned char th_lenres; //4位首部長度/6位保留字
unsigned char th_flag; //6位標志位
USHORT th_win; //16位窗口大小
USHORT th_sum; //16位校驗和
USHORT th_urp; //16位緊急數據偏移量
}TCP_HEADER;
struct //定義TCP偽首部
{
unsigned long saddr; //源地址
unsigned long daddr; //目的地址
char mbz;
char ptcl; //協議類型
unsigned short tcpl; //TCP長度
}psd_header;
//SOCK錯誤處理程序
void CheckSockError(int iErrorCode, char *pErrorMsg)
{
if(iErrorCode==SOCKET_ERROR)
{
printf("%s Error:%d\n", pErrorMsg, GetLastError());
closesocket(sockRaw);
ExitProcess(-1);
}
}
//計算檢驗和
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);
}
//IP解包程序
bool DecodeIPHeader(char *buf, int bytes)
{
IP_HEADER *iphdr;
TCP_HEADER *tcphdr;
unsigned short iphdrlen;
iphdr = (IP_HEADER *)buf;
iphdrlen = sizeof(unsigned long) * (iphdr->h_lenver & 0xf);
tcphdr = (TCP_HEADER*)(buf + iphdrlen);
//是否來自目標IP
if(iphdr->sourceIP != dest.sin_addr.s_addr) return false;
//序列號是否正確
if((ntohl(tcphdr->th_ack) != (SEQ+1)) && (ntohl(tcphdr->th_ack) != SEQ)) return false;
//if(tcphdr->th_flag == 20)return true;
//SYN/ACK - 掃描到一個埠
if(tcphdr ->th_flag == 18)
{
printf("\t%d\t open \n",ntohs(tcphdr->th_sport));
return true;
}
return true;
}
void usage(void)
{
printf("\t===================SYN portscaner======================\n");
printf("\[email protected] 2004/7/6===========\n");
printf("\tusage: synscan DomainName[IP] StartPort-EndPort\n");
printf("\tExample: synscan www.163.com 1-139\n");
printf("\tExample: synscan 192.168.1.1 8000-9000\n");
}
DWORD WINAPI RecvThread(LPVOID para)//接收數據線程函數
{
int iErrorCode;
struct hostent *hp;
char RecvBuf[65535]={0};
sockListen = socket(AF_INET , SOCK_RAW , IPPROTO_IP);
CheckSockError(sockListen, "socket");
//設置IP頭操作選項
BOOL bOpt = true;
iErrorCode = setsockopt(sockRaw,IPPROTO_IP,IP_HDRINCL,(char *)&bOpt,sizeof(bOpt));
CheckSockError(iErrorCode, "setsockopt()");
//獲得本地IP
SOCKADDR_IN sa;
unsigned char LocalName[256];
iErrorCode = gethostname((char*)LocalName,sizeof(LocalName)-1);
CheckSockError(iErrorCode, "gethostname()");
if((hp = gethostbyname((char*)LocalName)) == NULL)
{
CheckSockError(SOCKET_ERROR, "gethostbyname()");
}
memcpy(&sa.sin_addr.S_un.S_addr,hp->h_addr_list[1],hp->h_length);
sa.sin_family = AF_INET;
sa.sin_port = htons(7000);
iErrorCode = bind(sockListen, (PSOCKADDR)&sa, sizeof(sa));
CheckSockError(iErrorCode, "bind");
//設置SOCK_RAW為SIO_RCVALL,以便接收所有的IP包
DWORD dwBufferLen[10] ;
DWORD dwBufferInLen = 1 ;
DWORD dwBytesReturned = 0 ;
iErrorCode=WSAIoctl(sockListen, SIO_RCVALL,&dwBufferInLen, sizeof
(dwBufferInLen),&dwBufferLen, sizeof(dwBufferLen),&dwBytesReturned , NULL , NULL );
CheckSockError(iErrorCode, "Ioctl");
memset(RecvBuf, 0, sizeof(RecvBuf));
//接收數據
for(;;)
{
iErrorCode = recv(sockListen, RecvBuf, sizeof(RecvBuf), 0);
//CheckSockError(iErrorCode, "recv");
DecodeIPHeader(RecvBuf,iErrorCode) ;
}
if(ScanOK)
{
closesocket(sockListen);
return 0;
}
}
void playx(void) // 定義狀態提示函數
{
// 進度條
char *plays[12]=
{
" | ",
" / ",
" - ",
" \\ ",
" | ",
" / ",
" - ",
" \\ ",
" | ",
" / ",
" - ",
" \\ ",
};
printf(" =%s=\r", plays[play]);
play=(play==11)?0:play+1;
Sleep(2);
}
//主函數
int main(int argc,char **argv)
{
char *p;
if(argc!=3)
{
usage();
return 0;
}
p=argv[2];//處理埠參數
if(strstr(argv[2],"-"))
{ DEST_PORT=atoi(argv[2]);
for(;*p;)
if(*(p++)=='-')break;
DEST_PORTEND=atoi(p);
if(DEST_PORT<1 || DEST_PORTEND>65535)
{ printf("Port Error!\n");
return 0;
}
}
DEST_HOST=argv[1];
usage();
int iErrorCode;
int datasize;
struct hostent *hp;
IP_HEADER ip_header;
TCP_HEADER tcp_header;
char SendBuf[128]={0};
//初始化SOCKET
WSADATA wsaData;
iErrorCode = WSAStartup(MAKEWORD(2,2),&wsaData);
CheckSockError(iErrorCode, "WSAStartup()");
sockRaw = socket(AF_INET , SOCK_RAW , IPPROTO_IP);
CheckSockError(sockRaw, "socket()");
sockListen = socket(AF_INET , SOCK_RAW , IPPROTO_IP);
CheckSockError(sockListen, "socket");
//設置IP頭操作選項
BOOL bOpt = true;
iErrorCode = setsockopt(sockRaw,IPPROTO_IP,IP_HDRINCL,(char *)&bOpt,sizeof(bOpt));
CheckSockError(iErrorCode, "setsockopt()");
//獲得本地IP
SOCKADDR_IN sa;
unsigned char LocalName[256];
iErrorCode = gethostname((char*)LocalName,sizeof(LocalName)-1);
CheckSockError(iErrorCode, "gethostname()");
if((hp = gethostbyname((char*)LocalName)) == NULL)
{
CheckSockError(SOCKET_ERROR, "gethostbyname()");
}
memcpy(&sa.sin_addr.S_un.S_addr,hp->h_addr_list[1],hp->h_length);
sa.sin_family = AF_INET;
sa.sin_port = htons(7000);
iErrorCode = bind(sockListen, (PSOCKADDR)&sa, sizeof(sa));
CheckSockError(iErrorCode, "bind");
//獲得目標主機IP
memset(&dest,0,sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(DEST_PORT);
if((dest.sin_addr.s_addr = inet_addr(DEST_HOST)) == INADDR_NONE)
{
if((hp = gethostbyname(DEST_HOST)) != NULL)
{
memcpy(&(dest.sin_addr),hp->h_addr_list[1],hp->h_length);
dest.sin_family = hp->h_addrtype;
printf("dest.sin_addr = %s\n",inet_ntoa(dest.sin_addr));
}
else
{
CheckSockError(SOCKET_ERROR, "gethostbyname()");
}
}
//開啟監聽線程
HANDLE Thread=CreateThread(NULL,0,RecvThread,0,0,0);
//填充IP首部
ip_header.h_lenver=(4<<4 | sizeof(ip_header)/sizeof(unsigned long));
//高四位IP版本號,低四位首部長度
ip_header.total_len=htons(sizeof(IP_HEADER)+sizeof(TCP_HEADER)); //16位總長度(位元組)
ip_header.ident=1; //16位標識
ip_header.frag_and_flags=0; //3位標志位
ip_header.ttl=128; //8位生存時間TTL
ip_header.proto=IPPROTO_TCP; //8位協議(TCP,UDP…)
ip_header.checksum=0; //16位IP首部校驗和
ip_header.sourceIP=sa.sin_addr.s_addr; //32位源IP地址
ip_header.destIP=dest.sin_addr.s_addr; //32位目的IP地址
//填充TCP首部
tcp_header.th_sport=htons(7000); //源埠號
tcp_header.th_lenres=(sizeof(TCP_HEADER)/4<<4|0); //TCP長度和保留位
tcp_header.th_win=htons(16384);
//填充TCP偽首部(用於計算校驗和,並不真正發送)
psd_header.saddr=ip_header.sourceIP;
psd_header.daddr=ip_header.destIP;
psd_header.mbz=0;
psd_header.ptcl=IPPROTO_TCP;
psd_header.tcpl=htons(sizeof(tcp_header));
Sleep(500);
printf("\n");
printf("Scaning %s\n",DEST_HOST);
start=clock();//開始計時
for(;DEST_PORT<DEST_PORTEND;DEST_PORT++)
{
playx();
tcp_header.th_dport=htons(DEST_PORT); //目的埠號
tcp_header.th_ack=0; //ACK序列號置為0
tcp_header.th_flag=2; //SYN 標志
tcp_header.th_seq=htonl(SEQ); //SYN序列號
tcp_header.th_urp=0; //偏移
tcp_header.th_sum=0; //校驗和
//計算TCP校驗和,計算校驗和時需要包括TCP pseudo header
memcpy(SendBuf,&psd_header,sizeof(psd_header));
memcpy(SendBuf+sizeof(psd_header),&tcp_header,sizeof(tcp_header));
tcp_header.th_sum=checksum((USHORT *)SendBuf,sizeof(psd_header)+sizeof(tcp_header));
//計算IP校驗和
memcpy(SendBuf,&ip_header,sizeof(ip_header));
memcpy(SendBuf+sizeof(ip_header),&tcp_header,sizeof(tcp_header));
memset(SendBuf+sizeof(ip_header)+sizeof(tcp_header),0,4);
datasize=sizeof(ip_header)+sizeof(tcp_header);
ip_header.checksum=checksum((USHORT *)SendBuf,datasize);
//填充發送緩沖區
memcpy(SendBuf,&ip_header,sizeof(ip_header));
//發送TCP報文
iErrorCode=sendto(sockRaw,SendBuf,datasize,0,(struct sockaddr*) &dest,
sizeof(dest));
CheckSockError(iErrorCode, "sendto()");
}
end=clock();//計時結束
ScanOK=TRUE;
printf("Closeing Thread.....\n");
WaitForSingleObject(Thread,5000);
CloseHandle(Thread);
costtime= (float)(end - start) / CLOCKS_PER_SEC; //轉換時間格式
printf("Cost time:%f Sec",costtime);//顯示耗時
//退出前清理
if(sockRaw != INVALID_SOCKET) closesocket(sockRaw);
WSACleanup();
return 0;
}
『柒』 求助:如何用c語言完成ping命令功能
//呵呵調用個系統函數不就ok了?有興趣的話可以加我qq,
//大家一起探討.qq:237263394
#include<stdlib.h>
#include<stdio.h>
main()
{
char command[128];
while(1)
{printf("Command:");
fgets(command,128,stdin);
if(command[0]=='\n'||command[0]=='q')
exit(0);
system(command);
}
return 0;
}
『捌』 請教如何用C語言實現ping命令
如果你想獲取到Ping的結果
那麼直接system 調用ping或者popen調用即可。
如果想自己實現,就需要用socket自行發Ping包,並獲取回應
這個就很麻煩了。 建議可以看一下gnu ping的源碼,或者busybox的ping部分代碼。
『玖』 如何用C語言實現Ping程序功能
windows編程比較煩
讀取記事本,讀入IP
system("ping xx.xx.xx.xx > text.txt");
再讀取text.txt,分析裡面的速度值,取平均值,再跟剛才讀到的IP拼成字元串輸出。
linux上會簡單很多, sed+ping 就可以搞定了
『拾』 怎麼用C語言實現ping命令
可以直接調用shell命令 system("ping 192.******"); 2.自己寫一個程序發一個ICMP包