
最近手頭有點(diǎn)工作跟這個(gè)有段, 就實(shí)現(xiàn)一個(gè)簡(jiǎn)單ping. 不需要像源碼那么詳細(xì). 就實(shí)現(xiàn)如圖功能就行.
先說下原理:
-
使用
ICMP協(xié)議, 組織ICMP包socket_id = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
告訴host我們要使用發(fā)送的報(bào)文是ICMP, 至于怎么發(fā), 以及TCP通信的就是不是我們這里要關(guān)心的了 組織
ICMP標(biāo)示
p_icmp = (struct icmp *)buffer;
p_icmp->icmp_type = ICMP_ECHO;
p_icmp->icmp_code = 0;
p_icmp->icmp_cksum = 0;
p_icmp->icmp_seq = 12345;
p_icmp->icmp_id = getpid();
p_icmp->icmp_cksum = checkSum((uint16_t*)p_icmp, 64);
這里組織我們需要的ICMP的一些標(biāo)示
- 發(fā)送ICMP給host
int send_chars = sendto(socket_id, (char *)buffer, 64, 0, (struct sockaddr*) &to, (socklen_t) sizeof(struct sockaddr_in));
發(fā)送ICMP包給你host
- 等待
host的ICMP響應(yīng)包
int res = select(socket_id+1, &rfds, NULL, NULL, &tv);
receive_bytes = recvfrom(socket_id, packet, 1024, 0, (struct sockaddr *)&from, &fromlen)
等待host的響應(yīng)
基本上這樣一個(gè)簡(jiǎn)單的PING就可以了, 至于TCP之間的如何通信問題, 請(qǐng)查看SOCKET通信的相關(guān)資料
詳細(xì)代碼請(qǐng)查看我的github
參考文檔:
https://www.cs.utah.edu/~swalton/listings/sockets/programs/part4/chap18/ping.c