IP和ICMP的关系是怎样的? 10C

Frame 106: 102 bytes on wire (816 bits), 102 bytes captured (816 bits) on interface 0
Ethernet II, Src: 00:fe:ed:c0:ff:ee (00:fe:ed:c0:ff:ee), Dst: IntelCor_d7:50:28 (30:3a:64:d7:50:28)
Internet Protocol Version 4, Src: 185.134.131.106, Dst: 10.24.70.66
Internet Control Message Protocol

是不是下面的这种机制?:
DestinationA--->IP里面包含数据---------------------------->DestinationB
-----------------------出现错误--------------------------------------
DestinationA<-------------ICMP-----------------<---DestinationB

ICMP 封装成IP,是不是协议的那个位置填上ICMP? 还是以其他的形式?
ARM是怎样在这个中间是怎样寻址的?

3个回答

ICMP即Internet控制报文协议,它是IP的一部分,在每个IP软件模块中都包含了ICMP的实现。当IP报文传输出错时,路由器就向发送报文的源主机发送ICMP报文报告出错情况。ICMP报文使用IP报文来传输差错及控制报文,因此ICMP报文也可能丢失。ICMP报文的最终接收方是目的端主机上的IP模块。

ICMP为什么是IP层协议?我的理解是:对于两个主机通信,其端到端可控制的最底层是传输层(TCP/UDP),而ICMP可用于中间网络节点(如路由器)向源主机发送相关差错信息。所以是属于网络IP层的协议。

  1. ICMP 封装成IP,是不是协议的那个位置填上ICMP? 还是以其他的形式?

维基百科说 ICMP 协议是 IP 协议的一部分。实际上 ICMP 协议是在 IP 协议基础上实现的。
ICMP 报文存放在 IP 协议包的数据部分。
IP 协议包协议字段实际上只是指定其数据部分携带的协议是什么的一个标识符。如果该 IP 包携带的是 ICMP 数据报,则协议字段为 1。

  1. ARM是怎样在这个中间是怎样寻址的?

ARM? 你想说的是 ARP 吧? ARP 协议正常运作啊,ICMP 和 ARP 之间是没有冲突。

参考:
ICMP 协议: https://blog.csdn.net/yanglingwell/article/details/82989152
ARP 协议:https://blog.csdn.net/yanglingwell/article/details/82084662
IP 协议: https://blog.csdn.net/yanglingwell/article/details/82290089

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

icmp收包,把IP头给拆了 只留下icmp报文 请大神解释一下啊

int icmp_unpack(char* buf, int len) { int iphdr_len; struct timeval begin_time, recv_time, offset_time; int rtt; //round trip time struct ip* ip_hdr = (struct ip *)buf; iphdr_len = ip_hdr->ip_hl*4; struct icmp* icmp = (struct icmp*)(buf+iphdr_len); //使指针跳过IP头指向ICMP头** len-=iphdr_len; //icmp包长度 if(len < 8) //判断长度是否为ICMP包长度 { fprintf(stderr, "Invalid icmp packet.Its length is less than 8\n"); return -1; }

Smurf攻击问题,引用的代码如下,为什么只有将受害地址设置为本地IP才有ICMP数据包,求解。

#include "stdio.h" #include "winsock2.h" #include <ws2tcpip.h> #pragma comment (lib,"ws2_32") typedef struct _icmp_heAder { char type; char code; USHORT checksum; USHORT id; USHORT sequence; ULONG timestAmp; }ICMP_HEADER; //-------------------------------------------------------------------- typedef struct _ip_heAder { unsigned char ip_verlen; // 4-bit IPv4 version // 4-bit header length (in 32-bit words) unsigned char ip_tos; // IP type of service unsigned short ip_totallength; // Total length unsigned short ip_id; // Unique identifier unsigned short ip_offset; // Fragment offset field unsigned char ip_ttl; // Time to live unsigned char ip_protocol; // Protocol(TCP,UDP etc) unsigned short ip_checksum; // IP checksum unsigned int ip_srcaddr; // Source address unsigned int ip_destaddr; // Source address } IP_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); } //-------------------------------------------------------------------- int main(int Argc,char* Argv[]) { WSADATA WSADAtA; SOCKET RAwSock; int TimeOut; BOOL HAdHeAder; BOOL IsBrocAst; IP_HEADER ip_heAder; ICMP_HEADER icmp_heAder; char Buff[sizeof(IP_HEADER)+sizeof(ICMP_HEADER)+20]; struct sockaddr_in SAddr={0},dAddr={0}; if (WSAStartup(MAKEWORD(2,2),&WSADAtA)){ printf("WSAStArtup fAiled:%d\n",GetLastError()); return -1; } if ((RAwSock=socket(AF_INET,SOCK_RAW,255))==INVALID_SOCKET){ printf("socket fAiled:%d\n",GetLastError()); return -1; } TimeOut = 500; if (setsockopt(RAwSock,SOL_SOCKET,SO_SNDTIMEO,(char*)&TimeOut,sizeof(TimeOut))){ printf("setsockopt sendtimeout fAiled:%d\n",GetLastError()); return -1; } if (setsockopt(RAwSock,SOL_SOCKET,SO_RCVTIMEO,(char*)&TimeOut,sizeof(TimeOut))){ printf("setsockopt recvtimeout fAiled:%d\n",GetLastError()); return -1; } HAdHeAder = TRUE; if (setsockopt(RAwSock,IPPROTO_IP,IP_HDRINCL,(char*)&HAdHeAder,sizeof(HAdHeAder))){ printf("setsockopt IP_HDRINCL fAiled:%d\n",GetLastError()); return -1; } IsBrocAst = TRUE; if (setsockopt(RAwSock,SOL_SOCKET,SO_BROADCAST,(char*)&IsBrocAst,sizeof(IsBrocAst))){ printf("setsockopt IP_HDRINCL fAiled:%d\n",GetLastError()); return -1; } //Buff = malloc(sizeof(IP_HEADER)+sizeof(ICMP_HEADER)+20); //ip_heAder = (IP_HEADER*)Buff; /////fill ip_heAder ip_heAder.ip_verlen=(4<<4 | sizeof(IP_HEADER)/sizeof(unsigned long)); //ip_heAder.ihl = 5; ip_heAder.ip_tos = 0; ip_heAder.ip_totallength = htons(sizeof(IP_HEADER)+sizeof(ICMP_HEADER)+20); ip_heAder.ip_id = 0; //ip_heAder.frAg_off = 0; ip_heAder.ip_offset = 0; ip_heAder.ip_ttl = 255; ip_heAder.ip_protocol = IPPROTO_ICMP; ip_heAder.ip_srcaddr = inet_addr("x.x.x.x"); ip_heAder.ip_destaddr = inet_addr("x.x.x.255"); //ip_heAder.checksum = checksum((USHORT*)&ip_heAder,sizeof(IP_HEADER)); /////////////////// //icmp_heAder = (ICMP_HEADER*)(Buff+sizeof(IP_HEADER)); //////fill icmp_heAder icmp_heAder.type = 8; icmp_heAder.code = 0; icmp_heAder.id = htons(0); icmp_heAder.sequence = 0; //icmp_heAder.checksum = 0; icmp_heAder.checksum = 0;//checksum((USHORT*)(Buff+sizeof(IP_HEADER)),(sizeof(ICMP_HEADER)+20)); ////////////////////// SAddr.sin_family = AF_INET; SAddr.sin_addr .S_un .S_addr = ip_heAder.ip_destaddr ; SAddr.sin_port = htons (0); /////////////////////////////ÔÚicmpͷûÓÐÌîÊý¾Ýʱ,,icmpµÄchecksum×ÜÊdzö´í ????? memcpy(Buff,&ip_heAder,sizeof(IP_HEADER)); memcpy(Buff+sizeof(IP_HEADER),&icmp_heAder,(sizeof(ICMP_HEADER)+20));//20 memset(Buff+sizeof(IP_HEADER)+sizeof(ICMP_HEADER),'A',20); ip_heAder.ip_checksum = checksum((USHORT*)Buff,sizeof(Buff)); icmp_heAder.checksum = checksum((USHORT*)(Buff+sizeof(IP_HEADER)),(sizeof(ICMP_HEADER)+20)); memcpy(Buff,&ip_heAder,sizeof(IP_HEADER)); memcpy(Buff+sizeof(IP_HEADER),&icmp_heAder,(sizeof(ICMP_HEADER)+20));//20 memset(Buff+sizeof(IP_HEADER)+sizeof(ICMP_HEADER),'A',20); /////////////////////////////////////////////////////////////////////////// while(1){ //Sleep(200); if (!sendto(RAwSock,Buff,sizeof(Buff),0,(struct sockaddr*)&SAddr,sizeof(SAddr))){ printf("send fAiled:%d/n",GetLastError()); return -1; } } closesocket(RAwSock); WSACleanup(); return 0; }

ICMP的标识符和序列号的本质是什么?

4 0.471102408 10.24.70.66 115.239.210.27 ICMP 1066 Echo (ping) request id=0x1a20, seq=11/2816, ttl=64 (reply in 8) Internet Control Message Protocol Type: 8 (Echo (ping) request) //request 是8 ,reply 是0 Code: 0 Checksum: 0x3da0 [correct] // 校验码 [Checksum Status: Good] // 防止有人而已篡改 Identifier (BE): 6688 (0x1a20) Identifier (LE): 8218 (0x201a) Sequence number (BE): 11 (0x000b) Sequence number (LE): 2816 (0x0b00) [Response frame: 8] Timestamp from icmp data: Apr 1, 2018 17:27:53.000000000 CEST [Timestamp from icmp data (relative): 0.860325254 seconds] Data (1016 bytes) Data: 90200d0000000000101112131415161718191a1b1c1d1e1f... [Length: 1016] 8 0.828236910 115.239.210.27 10.24.70.66 ICMP 1066 Echo (ping) reply id=0x1a20, seq=11/2816, ttl=46 (request in 4) 上面的这个是ICMP的request and replay Internet Control Message Protocol Type: 0 (Echo (ping) reply) Code: 0 Checksum: 0x45a0 [correct] [Checksum Status: Good] Identifier (BE): 6688 (0x1a20) Identifier (LE): 8218 (0x201a) Sequence number (BE): 11 (0x000b) Sequence number (LE): 2816 (0x0b00) [Request frame: 4] [Response time: 357,135 ms] Timestamp from icmp data: Apr 1, 2018 17:27:53.000000000 CEST [Timestamp from icmp data (relative): 1.217459756 seconds] Data (1016 bytes) Data: 90200d0000000000101112131415161718191a1b1c1d1e1f... [Length: 1016] 我在抓包的过程中发现这个iddentifier 是一样的,但是这个Sequence number却是不一样的,这两个参数的本质是什么?

为什么icmp报文默认为56

1.为什么icmp报文默认为56,是因为收到的ip数据包首部20+8 +icmp首部8+发送的ip数据包首部20=50吗? 2.若不是 是否  发送的全部数据为 icmp报文56 + icmp首部8 + ip首部20 + 以太网首部14,tcp/ip卷一 ping那里估算往返时延时为什么没加 以太网首部14

Linux抓icmp包分析错误?

用Linux编程编写抓包协议,分析icmp报文的时候都是0 ``` else if(p_iphdr->protocol==1){ struct icmphdr*p_icmphdr=(struct icmphdr*)(p_iphdr+p_iphdr->ihl*4); if((p_icmphdr->icmp_type)==3||5||11||12){ printf("----这个是ICMP差错报告报文----\n"); }else{ printf("----这个是ICMP询问报文----\n"); } printf("type = %d\n ", p_icmphdr->icmp_type); printf("code = %d\n ", p_icmphdr->icmp_code); printf("id = %d\n ", p_icmphdr->icmp_id); printf("icmp_seq = %s\n ", ntohs(p_icmphdr->icmp_seq)); //输出序列号 ``` 这个是icmp结构体 ``` struct icmphdr { u_int8_t icmp_type; u_int8_t icmp_code; u_int16_t icmp_checksum; union { struct ih_idseq { u_int16_t icd_id; u_int16_t icd_seq; }ih_idseq; }icmp_hun; #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq //u32 icmp_timestamp[2];//时间戳 //ICMP数据占位符 u_int8_t data[0]; }; ``` 结果是这样 ![图片说明](https://img-ask.csdn.net/upload/201912/22/1576949050_718673.png) 这个icmp报文是我用ping网站获取的 求大佬告知小白一个,感谢

您可以使用icmp定位特定端口吗?

<div class="post-text" itemprop="text"> <p>I believe the title is pretty self explanatory, but just in case, I'll explain further. </p> <p>I am writing a function in Go that uses icmp to check if a particular service is running. I got this idea from ping implemented in Go. When I try command line ping, it can not resolve <code>127.0.0.1:8080</code>, and the function follows suit, which makes sense. But can I use icmp to check that address and port with something I missing? Or should I just stick something like tcp to target a port?</p> <p>Right now I have this simple function, and I <em>could</em> just use tcp, but I'm curious if I could use something like icmp.</p> <pre><code>func (c *Controller) Ping() error { conn, connErr := net.Dial("ip4:icmp", c.APIServerIP) if connErr != nil { return connErr } conn.SetDeadline(time.Now().Add(3 * time.Second)) defer conn.Close() return nil } </code></pre> </div>

windows自带的ping和用ICMP实现的ping有什么区别

为什么windows自带的ping不需要管理员权限,普通权限cmd就能运行,但是自己用ICMP实现的ping一定要管理员权限才能运行 是在实现上用的不同函数,还是系统自带的ping默认的就是管理员权限?

无法在Golang中解析icmp消息

<div class="post-text" itemprop="text"> <p>I'm a newb with Golang and trying to do what seems like a very simple task -- sending a ping with some text in it and reading that text back when I get a reply, but I'm running into some things I don't understand. I've built a ping like this:</p> <pre><code> ping := icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &amp;icmp.Echo{ ID: os.Getpid() &amp; 0xffff, Seq: 1, Data: []byte("Hello"), }, } </code></pre> <p>Here's the socket read part for context:</p> <pre><code>buf := make([]byte, 1500) _, peer, err := c.ReadFrom(buf) message, err := icmp.ParseMessage(1, buf) </code></pre> <p>Here's my failed effort to get my data back out of the message body:</p> <pre><code>body := message.Body; fmt.Println("body.ID ", body.ID) fmt.Println("body.Seq ", body.Seq) fmt.Println("body.Data ", string(body.Data)) </code></pre> <p>Go is not happy at build time:</p> <pre><code>./ping.go:86: body.ID undefined (type icmp.MessageBody has no field or method ID) ./ping.go:87: body.Seq undefined (type icmp.MessageBody has no field or method Seq) ./ping.go:88: body.Data undefined (type icmp.MessageBody has no field or method Data) </code></pre> <p>This code, however, which is adapted from <a href="https://github.com/tatsushid/go-fastping/blob/master/fastping.go#L649-L658" rel="nofollow">this awesome project</a>, works just swell:</p> <pre><code>switch body := message.Body.(type) { case *icmp.Echo: fmt.Println("body.ID ", body.ID) fmt.Println("body.Seq ", body.Seq) fmt.Println("body.Data ", string(body.Data)) default: fmt.Println("not a *icmp.Echo") } </code></pre> <p>Go is perfectly happy to compile and run this code. Can someone tell me why the code in the type switch works fine, but the first example results in compile errors. Thank you!</p> </div>

ICMP参数问题报文如何传回源地址?

IP层数据报发生错误则丢弃是因为源地址可能发生错误,如果源地址错了如何发送参数问题报告报文。计算机网络教材中参数问题保报文中的解释为有的参数发生错误才会发送,可是只有首部检验和如何判断是哪个字段出了问题?

原始套接字未收到icmp响应

<div class="post-text" itemprop="text"> <p>I'm trying to send an icmp message whose TTL is just 1, and expect to receive a time exceeded message. that message does come(I see it from wireshark), but my program blocks on <code>syscall.Recvfrom</code>. Anyone knows why?<br> <strong>icmp.go</strong></p> <pre><code>package main import ( "bytes" "encoding/binary" "fmt" "net" "os" "syscall" ) type ICMP struct { Type uint8 Code uint8 Checksum uint16 Identifier uint16 SeqNo uint16 } func Checksum(data []byte) uint16 { var ( sum uint32 length int = len(data) index int ) for length &gt; 1 { sum += uint32(data[index])&lt;&lt;8 + uint32(data[index+1]) index += 2 length -= 2 } if length &gt; 0 { sum += uint32(data[index]) } sum += (sum &gt;&gt; 16) return uint16(^sum) } func main() { h := Header{ Version: 4, Len: 20, TotalLen: 20 + 8, TTL: 1, Protocol: 1, // Dst: } argc := len(os.Args) if argc &lt; 2 { fmt.Println("usage: program + host") return } ipAddr, _ := net.ResolveIPAddr("ip", os.Args[1]) h.Dst = ipAddr.IP icmpReq := ICMP{ Type: 8, Code: 0, Identifier: 0, SeqNo: 0, } out, err := h.Marshal() if err != nil { fmt.Println("ip header error", err) return } var icmpBuf bytes.Buffer binary.Write(&amp;icmpBuf, binary.BigEndian, icmpReq) icmpReq.Checksum = Checksum(icmpBuf.Bytes()) icmpBuf.Reset() binary.Write(&amp;icmpBuf, binary.BigEndian, icmpReq) fd, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW) addr := syscall.SockaddrInet4{ Port: 0, } copy(addr.Addr[:], ipAddr.IP[12:16]) pkg := append(out, icmpBuf.Bytes()...) fmt.Println("ip length", len(pkg)) if err := syscall.Sendto(fd, pkg, 0, &amp;addr); err != nil { fmt.Println("Sendto err:", err) } var recvBuf []byte if nBytes, rAddr, err := syscall.Recvfrom(fd, recvBuf, 0); err == nil { fmt.Printf("recv %d bytes from %v ", nBytes, rAddr) } } </code></pre> <p>additionally, I use <code>header.go</code> and <code>helper.go</code> from <a href="https://github.com/golang/net/tree/master/ipv4" rel="nofollow">https://github.com/golang/net/tree/master/ipv4</a></p> </div>

python导入scapy后,找不到IP这个类的定义,报错,怎么解决?

我用的是eclipse with pydev,写如下代码: ``` import scapy from scapy.all import all test_ip=IP(dst="192.168.1.1",src="192.168.1.2") ``` 但是报错: ![图片说明](https://img-ask.csdn.net/upload/201604/25/1461591235_654987.png) ![图片说明](https://img-ask.csdn.net/upload/201604/25/1461591405_885898.png) 第二张图是scapy.all里,没有IP的定义。这是怎么回事?我看网上的都是from scapy.all import * 就可以的啊

侦听所有IP数据包,包括ICMP,TCP和UDP?

<div class="post-text" itemprop="text"> <p>Specially in golang, there are interfaces like <code>net.ListenIP</code> and <code>net.ListenTCP</code>. </p> <p>I'm wondering that, if process p1 <code>ListenIP(192.168.1.1)</code> and process p2 <code>ListenTCP(192.168.1.1:80)</code>, will all packets dest to 192.168.1.1 (no matter TCP or UDP) are intercepted by p1, and p2 will never accept a TCP connection?</p> </div>

请问ICMP_ECHO是系统预定义的吗,包含在哪个头文件里呢?

在编写一个ping程序时,填充ICMP包的内容,要将类型设置为ICMP响应包,即icmp_hdr->i_type =ICMP_ECHO; 但是IDE提示未定义的标识符ICMP_ECHO未定义,这是怎么回事呢

IP数据报首部首部检验和的计算问题?

IPV4数据报的首部长度为5,数据总长度为80字节,数据报的标识为1,未分片, TTL值为4,封装的是TCP数据,源地址和目的地址分别是192.168.20.86和192.168.21.20, 请对IP数据报进行首部校验。

基于winpcap解析icmp数据包

基于winpcap解析icmp数据包,的c++代码,单独把主要函数写出来,程序能运行,

icmp.PacketConn在Windows下看不到TTL超过消息

<div class="post-text" itemprop="text"> <p>I'm trying to implement small traceroute utility as part of some crossplatform project. But I've found that under Windows, Go doesn't see any TTL exceed messages on raw icmp socket, despite the fact that I see those packets in wireshark.</p> <p>Here is a full test that passes under *nix and fails under Windows:</p> <pre class="lang-golang prettyprint-override"><code>package probes import ( "fmt" "net" "testing" "golang.org/x/net/icmp" "golang.org/x/net/ipv4" "time" ) func TestTtlExceed(t *testing.T) { conn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatalf("Cannot listen: %s", err.Error()) } defer conn.Close() go listen(conn, t) msg := icmp.Message{ Code: 0, Body: &amp;icmp.Echo{ Seq: 1, ID: 1, Data: []byte{'t','e','s','t'}, }, Type:ipv4.ICMPTypeEcho, } wbuf, err := msg.Marshal(nil) if err != nil { t.Fatalf("Failed to marshal: %s", err.Error()) } conn.IPv4PacketConn().SetTTL(1) err = conn.SetWriteDeadline(time.Now().Add(time.Second)) if err != nil { t.Fatalf("Failed to set dl: %s", err.Error()) } _, err = conn.WriteTo(wbuf, &amp;net.IPAddr{IP:net.ParseIP("8.8.8.8")}) if err != nil { t.Fatalf("Failed to write: %s", err.Error()) } time.Sleep(time.Second * 3) } func listen(conn *icmp.PacketConn, t *testing.T) { got := false conn.SetReadDeadline(time.Now().Add(time.Second * 2)) for { buf := make([]byte, 256) n, cm, peer, err := conn.IPv4PacketConn().ReadFrom(buf) if err != nil { // t.Fatalf("Error reading: %s", err.Error()) t.Logf("Error reading: %s", err.Error()) break } fmt.Printf("Got some: n: %v\tpeer:%s\tcm:%+#v ", n, peer.String(),cm) got = true /*buf := make([]byte, 256) n, peer, err := conn.ReadFrom(buf) if err != nil { t.Fatalf("Listen failed: %s ", err.Error()) return } fmt.Printf("icmp: got ") parsed, err := icmp.ParseMessage(1, buf[:n]) if err != nil { t.Fatalf("Failed to parse icmp message: %s", err.Error()) return } fmt.Printf("Got message from %s: %+#v ", peer.String(), parsed)*/ } if !got { t.Fatalf("Got nothing from conn") } } </code></pre> <p>Any ideas about what's wrong with windows icmp raw socket?</p> </div>

用C语言实现的traceroute设置IP数据报TTL无效,这是为什么?

用C语言实现的traceroute程序,发送ICMP请求报文设置TTL从1到30,但是通过抓包工具发现发出去的ICMP数据包TTL都是64,这是为什么?

用python 中socket模块中的raw制造icmp包问题

![图片说明](https://img-ask.csdn.net/upload/201911/20/1574256246_128807.png) 这是icmp包 校验和程序,我想不明白,最后return校验和,为什么要&ffff. 第一个sum &ffff是为了取最后16位 第二个sum &ffff类似第一个,为了保证多出来的也被计算。

C#网络通信程序设计基于ICMP的活动主机探测程序设计如何在界面上显示PING的统计结果(成功,失败次数)

C#网络通信程序设计基于ICMP的活动主机探测程序设计如何在界面上显示PING的统计结果(成功,失败次数) 用的是visual studio 2010 下面是窗体程序 ![图片说明](https://img-ask.csdn.net/upload/201903/31/1554009839_587560.png) 下面是代码 program ``` using System; using System.Collections.Generic; using System.Windows.Forms; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Net; using System.Net.Sockets; namespace pingProgram { public class IcmPacket { private Byte my_type; private Byte my_subCode; private UInt16 my_checkSum; private UInt16 my_identifier; private UInt16 my_sequenceNumber; private Byte[] my_data; public IcmPacket(Byte type, Byte subCode, UInt16 checkSum, UInt16 identifier, UInt16 sequenceNumber, int dataSize) { my_type = type; my_subCode = subCode; my_checkSum = checkSum; my_identifier = identifier; my_sequenceNumber = sequenceNumber; my_data = new Byte[dataSize]; for (int i = 0; i < dataSize; i++) { my_data[i] = (byte)'k'; } } public UInt16 CheckSum { get { return my_checkSum; } set { my_checkSum=value; } } public int CountByte(Byte[] buffer) { Byte[] b_type = new Byte[1] { my_type }; Byte[] b_code = new Byte[1] { my_subCode }; Byte[] b_cksum = BitConverter.GetBytes(my_checkSum); Byte[] b_id = BitConverter.GetBytes(my_identifier); Byte[] b_seq = BitConverter.GetBytes(my_sequenceNumber); int i = 0; Array.Copy(b_type, 0, buffer, i, b_type.Length); i += b_type.Length; Array.Copy(b_code, 0, buffer, i, b_code.Length); i += b_code.Length; Array.Copy(b_cksum, 0, buffer, i, b_cksum.Length); i += b_cksum.Length; Array.Copy(b_id, 0, buffer, i, b_id.Length); i += b_id.Length; Array.Copy(b_seq, 0, buffer, i, b_seq.Length); i += b_seq.Length; Array.Copy(my_data, 0, buffer, i, my_data.Length); i += my_data.Length; return i; } public static UInt16 SumOfCheck(UInt16[] buffer) { int cksum = 0; for (int i = 0; i < buffer.Length; i++) cksum += (int)buffer[i]; cksum = (cksum >> 16) + (cksum & 0xffff); cksum += (cksum >> 16); return (UInt16)(~cksum); } } static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } ``` form1 ``` using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace pingProgram { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnPing_Click(object sender, EventArgs e) { listBox1.Items.Clear(); if (textBox1.Text == "") { MessageBox.Show("IP地址不能为空!"); return; } string Hostclient = textBox1.Text; Socket Socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); Socket.ReceiveTimeout = 1000; IPHostEntry Hostinfo; try { Hostinfo = Dns.GetHostEntry(Hostclient); } catch (Exception) { listBox1.Items.Add("无法辨识主机!"); return; } EndPoint Hostpoint = (EndPoint)new IPEndPoint(Hostinfo.AddressList[0], 0); IPHostEntry Clientinfo; Clientinfo = Dns.GetHostEntry(Hostclient); EndPoint Clientpoint = (EndPoint)new IPEndPoint(Clientinfo.AddressList[0], 0); int DataSize = 4; int PacketSize = DataSize + 8; const int Icmp_echo = 8; IcmPacket Packet = new IcmPacket(Icmp_echo, 0, 0, 45, 0, DataSize); Byte[] Buffer = new Byte[PacketSize]; int index = Packet.CountByte(Buffer); if (index != PacketSize) { listBox1.Items.Add("报文出现错误!"); return; } int Cksum_buffer_length = (int)Math.Ceiling(((Double)index)/2); UInt16[] Cksum_buffer = new UInt16[Cksum_buffer_length]; int Icmp_header_buffer_index = 0; for (int I = 0; I < Cksum_buffer_length; I++) { Cksum_buffer[I] = BitConverter.ToUInt16(Buffer, Icmp_header_buffer_index); Icmp_header_buffer_index += 2; } Packet.CheckSum = IcmPacket.SumOfCheck(Cksum_buffer); Byte[] SendData = new Byte[PacketSize]; index = Packet.CountByte(SendData); if (index != PacketSize) { listBox1.Items.Add("报文出现错误!"); return; } int pingNum=4; for (int i = 0; i < 4; i++) { int Nbytes = 0; int startTime = Environment.TickCount; try { Nbytes = Socket.SendTo(SendData, PacketSize, SocketFlags.None, Hostpoint); } catch (Exception) { listBox1.Items.Add("无法传送报文!"); return; } Byte[] ReceiveData = new Byte[256]; Nbytes = 0; int Timeconsume = 0; while (true) { try { Nbytes = Socket.ReceiveFrom(ReceiveData, 256, SocketFlags.None, ref Clientpoint); } catch (Exception) { listBox1.Items.Add("超时无响应!"); break; } if (Nbytes > 0) { Timeconsume = System.Environment.TickCount - startTime; if (Timeconsume < 1) listBox1.Items.Add("reply from: " + Hostinfo.AddressList[0].ToString() + " Send: " + (PacketSize + 20).ToString() + " time<1ms " + "bytes Received " + Nbytes.ToString()); else listBox1.Items.Add("reply from: " + Hostinfo.AddressList[0].ToString() + " Send: " + (PacketSize + 20).ToString() + " In " + Timeconsume.ToString() + " ms;bytes Received " + Nbytes.ToString()); break; } } } Socket.Close(); } private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog savedlg = new SaveFileDialog(); savedlg.Filter = "文本文件|*.txt"; savedlg.Title = "保存记录"; savedlg.ShowDialog(); if (savedlg.FileName != "") { string localFilePath; localFilePath = ""; localFilePath = savedlg.FileName.ToString(); string str = ""; for (int j = 0; j < listBox1.Items.Count; j++) { str += listBox1.Items[j].ToString() + "\r\n"; } FileStream fs = new FileStream(localFilePath, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.Write(str); sw.Flush(); sw.Close(); fs.Close(); MessageBox.Show(" PING结果保存完毕。 ","PING程序设计",MessageBoxButtons.OK); } } } } ```

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c# 按行txt c#怎么扫条形码 c#打包html c# 实现刷新数据 c# 两个自定义控件重叠 c#浮点类型计算 c#.net 中文乱码 c# 时间排序 c# 必备书籍 c#异步网络通信
立即提问