實現PING功能

2021-10-04 21:03:14 字數 3219 閱讀 9722

實現ping功能 具體細節可以看注釋

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define max_size 1024

char send_buf[max_size]

;char recv_buf[max_size]

;int nsend =

0, nrecv =0;

//計數器

int datalen =56;

//統計結果

void

statistics

(int signum)

//校驗和演算法

intcalc_chsum

(unsigned

short

*buf,

int len)

//處理資料大小是奇數,在最後乙個位元組後面補0

if(n ==1)

//將得到的sum值的高2位元組和低2位元組相加

sum =

(sum >>16)

+(sum &

0xffff);

//處理溢位的情況

sum +

= sum >>16;

answer =

~sum;

return answer;

}int

pack

(int pack_num)

packsize =

8+ datalen;

//icmp報頭8位元組

icmp-

>icmp_cksum =

calc_chsum((

unsigned

short

*)icmp, packsize)

;//計算校驗和

return packsize;

}int

send_packet

(int sockfd,

struct sockaddr *paddr)

return0;

}struct timeval time_sub

(struct timeval *tv_send,

struct timeval *tv_recv)

ts.tv_sec = tv_recv-

>tv_sec - tv_send-

>tv_sec;

ts.tv_usec = tv_recv-

>tv_usec - tv_send-

>tv_usec;

return ts;

}int

unpack

(int len,

struct timeval *tv_recv,

struct sockaddr *paddr,

char

*ipname)

//判斷是否全為傳送程序,回應icmp包if(

ntohs

(icmp-

>icmp_id)

==getpid()

&& icmp-

>icmp_type == icmp_echoreply)

return0;

}int

recv_packet

(int sockfd,

char

*ipname)

//ipname傳送方位址if(

gettimeofday

(&tv,

null

)<0)

unpack

(n,&tv,

&from_addr, ipname)

;return0;

}int

main

(int argc,

char

*ar**)

//獲取icmp資訊if(

(protocol =

getprotobyname

("icmp"))

==null

)//建立原始套接字if(

(sockfd =

socket

(af_inet, sock_raw, protocol-

>p_proto)

)<0)

//ip層原始套接字 ip包頭自動加封

//**root許可權,設定當前使用者許可權

setuid

(getuid()

);//擴大套接字接受緩衝區到50kb(見size),減少接受緩衝區溢位的可能性if(

setsockopt

(sockfd, sol_socket, so_rcvbuf,

&size,

sizeof

(size)

)<0)

//填充對方位址

bzero

(&peer_addr,

sizeof

(peer_addr));

peer_addr.sin_family = af_inet;

//判斷是主機名還是ip

//不是ipif(

(netaddr =

inet_addr

(ar**[1]

))== inaddr_none)

memcpy((

char*)

&peer_addr.sin_addr, host-

>h_addr, host-

>h_length);}

else

//註冊訊號處理函式

signal

(sigalrm, statistics)

;signal

(sigint, statistics)

;alarm(5

);//列印開始資訊

printf

("ping %s(%s) %d bytes of data.\n"

, ar**[1]

,inet_ntoa

(peer_addr.sin_addr)

, datalen)

;//傳送報文和接受報文

while(1

)exit

(exit_success)

;}

實現了ping功能,更加細節了解ip icmp包

c 實現ping功能

思路 首先新增乙個文字框,用來接收ip位址。用ipaddress myip ipaddress.parse textbox1.text.tostring 把文字框內容變成ip位址,寫到乙個異常中,就可以省略掉判斷ip位址是否正確了。定義乙個ping的方法 system.net.networkinfo...

C 下實現ping功能

ping的呼叫方法如下 ping mping new ping mping.pinging 127.0.0.1 255,65535 mping.receive 成功接收返回true,timeout 返回false 全部源 如下 using system using system.io using s...

Linux拓展應用之ping功能實現詳解

define max wait time 5 接收超時5秒 define max no packets 3 char sendpacket packet size char recvpacket packet size int sockfd,datalen 56 int nsend 0,nrecei...