Computer Network Course Design - Common Commands, Switches and Routers, Network Programming

  • Purpose and mission of the course

This course requires students to verify and deepen their understanding of computer network concepts on the basis of the theoretical study of "computer network principles". Through the practice of this course, the students' abilities of independent thinking, comprehensive analysis and hands-on practice will be cultivated.

Through the study of this course, the following objectives will be achieved:

(1). Understand the computer network architecture and working principles, master commonly used network commands, be able to explain the functions of commands, analyze the results of command execution, and draw reasonable and effective conclusions.

(2). Master the operation method of Packet Tracer software, be able to use the software to simulate networking, configure switches and routers, be able to implement simulation experiments according to the experimental plan, and collect and organize data.

(3). Possess network programming ability, be able to design a packet capture program to obtain data packets, analyze, process and interpret the meaning of each field of the data packet in combination with relevant protocols, and obtain effective conclusions.

  • Basic content and requirements of the course
    1. experimental theory
    2. Experimental content

1. (1) Functions of common network commands ipconfig, ping, netstat, tracert, arp, telnet :

 The following is a general description of each command :

ipconfig command: helps users to view network status and some related network configuration information, such as the IP address of the machine, subnet mask, DNS configuration, hardware address, etc.

Ping command: It is part of the TCP/IP protocol to determine whether datagrams can be exchanged between the local host and another host. We can judge whether the TCP/IP configuration is correct based on the returned information, and use it to detect the connectivity of the network.

netstat command: It is a DOS command used to monitor the TCP/IP network. It can display the routing table, the actual network connection and the status information of each network interface device, the protocol type adopted by the host user, the current host and the remote connected host. IP address and its connection status. It can let the user know which network connections are running. If used without parameters, it will display all active TCP connections of the machine.

arp command: the abbreviation of Address Resolution Protocol I (Source: Baidu Encyclopedia), used to display and modify the items in the "Address Resolution Protocol" cache, and display the current IP and physical address of the host. If the input does not have parameters, it will display the usage method of arp with parameters.

tracert command: When the computer transmits datagrams to the destination through multiple gateways, this command can be used to trace the router path that the datagram passes through, and to determine the path that the IP datagram visits the target. Enter the command without parameters to display How to use tracer with parameters.

Telnet command: It can be used to log in to the remote host system for remote desktop control .

  1. In the windows environment, use the above network commands to monitor and track the network status, and give corresponding screenshots and explanations of the results.

(1) Enter the ipconfig command in the networked and offline state respectively

   Figure 1-1 The interface after inputting ipconfig on the machine in the networked state

                   Figure 1-2 The interface after entering ipconfig in the state of disconnecting the network connection

When connecting to the network, it can be seen from Figure (1-1) that there is an available network connection. It can be seen that the IP address of the machine is 192.168.43.146 and the subnet mask is 255.255.255.0. After the network is disconnected, it can be seen from Figure (1-2) that there is no available network connection.

(2) ipconfig-all command

                    Figure 1-3 The interface after entering the ipconfig-all command in the networked state

ipconfig-all command: used to display all information related to the current IP configuration, as shown in Figure (1-3), including IP (192.168.43.146), server IP, MAC address (3E-91-80-71-34-09 ) (more parameters displayed than the ipconfig command), the host name (the local name is LAPOT-1JOM5AIJ).

(3) ipconfig-release command

                   Figure 1-4 The interface after entering the ipconfig-release command in the networked state

               Figure 1-5 and then enter ipconfig

After entering the ipconfig-release command and pressing Enter, the computer IP address is released, and the computer will be disconnected from the network (as shown in Figure 1-4, QQ is offline). At this time, enter the ipconfig command, which shows that the media has been disconnected, as shown in Figure (1-5). It can be seen that this command is used to release the IP address.

(4) ipconfig-renew command

              Figure 1-6 The interface after entering the ipconfig-renew command after the previous step

After entering ipconfig-renew and pressing Enter, you can re-acquire the local IP address (192.168.43.146), and the computer can reconnect to the network (as shown in Figure 1-6, QQ is online). This command is used to reassign an IP address to the host.

(5) ipconfig-flushdns command

                    Figure 1-6 The interface after entering the ipconfig-flushdns command on the command line

After entering the ipconfig-flushdns command and pressing Enter, the DNS cache of the machine is refreshed. This command is used to clear the local DNS cache content.

   ②

(1) ping +IP address

  Figure 2-1 Ping the IP address of the roommate in the networked state (failure)

As can be seen from Figure (2-1), the ping failed because we are not in the same network domain, so the ping fails.

   Figure 2-2 Successfully ping Baidu and Sohu in the networked state

It can be seen from Figure (2-2) that the success of pinging Baidu and Sohu is because their domain names and IPs are accessible.

(2) ping IP -a command

Figure 2-3 ping baidu -a get a reply

As can be seen from Figure (2-3) ping IP -a, this command can return the host name, we can check the host name through this command, and then quickly find the host.

(3) ping IP -i TTL command

 Figure 2-4ping baidu -i TTL command

As shown in (2-4), set the survival time to 53, this command is used to set the survival time to a specified value.

(4) ping IP -n count command

  Figure 2-5 ping baidu -n count command

As shown in (2-5), send data to baidu (target address) 5 times, that is, send data 5 times. This command is used to execute the ping command for the specified number of times.

(1) Enter the netstat command directly

Figure 3-1 Enter the netstat command without parameters

As shown in Figure (3-1), all active TCP connections (address, status, etc.) of the machine are displayed.

(2) netstat -a command

Figure 3-2 Enter the netstat -a command

As shown in (3-2), this command displays a list of all options of the machine, all network connections and listening ports, and all effective connection information .

(3) netstat -e command

 Figure 3-3 Enter the netstat -e command

As shown in (3-3), this command displays some extended information and statistics about Ethernet (such as the number of bytes, unicast data, discarded, etc.).

(4) netstat -s command

 Figure 3-4 Enter the netstat -s command

As shown in (3-4), this command displays the statistical data of each protocol (IPv4, IPv6..), and can also be used to check the network connection, data sending and receiving.

(5) netstat -r command

Figure 3-5 Enter netstat -r

As shown in Figure (3-5), this command is used to display the core routing table.

(1) arp command

  Figure 4-1 Enter the arp command

Figure (4-1) shows the main parameters and usage of the arp command.

(2) arp -a command

  Figure 4-2 arp -a command

As shown in the picture (4-2), 192.168.43.146 is the IP of the machine, which shows the IP address, physical address and type of the machine.

(3) arp -g command

 Figure 4-3 arp -g command

As shown in (4-2) and (4-3), we can see that this command is the same as -a.

(4)arp -a IP

Figure (4-4) arp -a IP

As can be seen from Figure (4-4), the arp -a IP command can record the list information of the specified IP address and physical address.

(5) arp -s command

 Figure 4-5 arp -s command

As shown in (4-5), an IP (192.168.22.22) and its physical address (A0-BB-CC-11-22-33) are added, and the information can be queried through the arp -a command. It can be seen that this command is used to add static items in the arp cache, and the IP address and physical address need to be specified. After using arp -a, the added information can be displayed.

(6)arp -d

Figure (4-6) arp -d command

As shown in Figure (4-6), after using arp -s to add a static item, it can be found, and then using arp -d to delete it, it cannot be found. It can be seen that this command is used to delete the specified ARP entry.

(1) Enter the tracert command

Figure 5-1 tracert command

As shown in Figure (1-15), all operation methods are displayed.

(2)tracert IP

 Figure 5-2 tracert Local IP

As shown in Figure (5-2), use this command to track the local IP, and the routing information and IP address from the local machine (192.168.43.146) to the local IP address are displayed.

Figure 5-3 tracert baidu 

As shown in Figure (5-3), the router information and IP address that the local machine needs to pass through to access Baidu are queried here, and * means timeout.

(3) tracert -d command

 Figure (5-4) tracert -d command

Comparing Figures (5-4) and (5-3), we can see that this command does not resolve IP addresses to host names.

(4) tracert -h maximum_hops command

  Figure (5-5) tracert -h 3 baidu

As shown in the figure (5-5), we can see that the parameter maximum is used to specify the maximum number of records for tracking the specified IP. In the figure, it is 3, which means that it has jumped three times.

(5) tracert -w timeout command

 Figure (5-6) input tracert -w 6 baidu

From Figure (5-6), we can see that parameter 6 specifies the number of milliseconds to wait for each reply from Baidu, which is the function of this command.

telnet

 Figure 6-1 telnet

(2) telnet ip port command

Used to check whether the port is accessible

 Figure 6-2 telnet local IP 139 (port number)

Figure 6-3 The interface after entering the port

As shown in Figure (6-1), now enter the netstat -a -n command on the command line to check which ports are open, and then enter telnet IP port (open) on the command line and enter "CTRL+]" to open the telnet session for operation. The interface is shown in Figure (6-3).

(3) send + character

 Figure (6-4) send 233444

After entering the port, enter send+string to send commands and data to the server, as shown in Figure (6-4).

(4)set ntlm和unset ntlm

  Figure (6-5) Some operation methods and operation interface of the set command

As shown in Figure (6-5), the set utlm command can perform authentication, and the unset utlm command can not perform authentication.

(5) close and quit

         

 Figure (6-6) The send character fails after inputting close

As shown in Figure (6-6), after entering close, the port is closed, so the send command fails because it is not connected.

(6)

display

 Figure (6-7)dispaly

This command is used to display the parameters of the current operation.

2.

  1. Install packet tracer, and familiarize yourself with switch commands and switch initialization configuration in the packet tracer simulation environment;

  Switch some basic commands:

Enter en to enter privileged mode

Switch# input conf t

            Enter vlan n to create a subnet

            Enter exit to exit

            Enter int fa n1/n2 to enter the n1/n2 port of the switch

            Enter switchport access vlan n to divide the port into n subnets

            Enter show vlan to view the subnet information divided by the port

(2) Realize VLAN configuration on the switch ;

Requirements: Create three VLANs, give topology, and view VLAN information

 The topology diagram is as follows:

   Figure (A-1) Network topology diagram

As shown in Figure (A-1), the IP address of each PC end of the network structure and the subnet where each end is located have been marked with the label function. It can be seen that PC3 and PC4 are in the same subnet VLAN4, PC1 and PC0 are in the same subnet VLAN2, and PC2 and PC5 are in the same subnet VLAN3.

The following figure (A-2-0) shows the subnet information displayed by the port after the command line show vlan

 Figure (A-2-0) show vlan

Test connectivity as follows:

  1. Try to ping PC1 and PC2 on the PC0 command line, as shown in the following figure (A-2-1), only PC1 (192.168.0.1) can be pinged, but PC2 (192.168.0.3) is not pinged because they are not in the same VLAN. PC2 can only ping PC5 (A-2-2)
  2. In Stimulation mode, PC0 sends a PUD, only PC1 can receive it. As shown in Figure (A-3) (A-4):

The PDU path shows that it is only sent to PC1.

    Figure (A-2-1) PC0ping PC1, and PC2

  Figure (A-2-2) 192.168.0.3ping 192.168.0.4 (success)/2 (failure)

    

Figure (A-3) in PC0 create PDU

Figure (A-4) PC0 sends a broadcast signal

Figure (A-5) PDU path

  1. Log in and configure the router based on the Console console, learn router configuration related commands; build a network environment based on packet tracer , and perform static routing configuration and RIP -based dynamic routing configuration respectively . Requirements: At least 4 routers in the static routing configuration topology .

Commands to configure the router:

First enter en to enter privileged mode

                  Type conf -t

  Router(config) input int fa n1/n2 to enter the port

  Router(config-if) Input ip add xxx.xxx.xxx.xxx (IP address) 255.2555.255.0 (subnet mask) to configure IP for this port

  Enter no shut to open the port

  Enter exit to exit

Static key commands:

  Router(config)# Input ip route 192.168.3.0 (destination IP) 255.255.255.0 192.168.2.2 (next hop IP port)

Dynamic key commands:

Router(config)# Enter router rip to start the RIP protocol

Router(config-router)# Enter network XXX.XXXX.XXX.XXX (IP address) to add dynamic routing

Router(config-router)# Enter network 192.168.0.0 such as this IP

Figure (B-1) is a topology diagram of the static routing network structure. The network corresponding to each interface has been marked, a total of 4 routers, 4 switches and 8 hosts.

  Figure (B-1) Static routing network structure topology

 Figure (B-2) information after each router show ip rou

Each router is configured with the IP of each interface and three next paths to the other three IP networks, as shown in Figure (B-2).

The following figure (B-3) shows the routing information that PC15 (192.168.1.2) tracert IP192.168.4.2 (PC13) passes through. It can be seen from the (B-1) topology diagram that it first passes through 192.168.1.1->192.168. 5.2 ->192.168.6.3 ->192.168.5.6->192.168.4.2. The path has been marked in the figure.

 

              Figure (B-3) PC15 (192.168.1.2) tracert IP192.168.4.2 (PC13)

   Figure (B-4) Path under Simulation

The path can be clearly shown in Figure (B-4).

 Figure (B-5) PC13 received, PC15 received the reply

It can be seen from Figure (B-5) that PC13 received the message sent by PC15, and then PC15 also received a reply from PC13. Can prove Unicom.

  1. In the RIP dynamic routing configuration, two paths with different hops are set between the source station and the destination station. After RIP configuration, check which path is selected.

The following figure (C-1) is a topology diagram of the dynamic routing network structure. The IP of each interface and the IP of the PC have been marked in the figure, a total of three routers (type 1841, because this router has only two interfaces, so it is necessary to add an interface artificially), and two hosts. The connection method and wiring are shown in the figure. Between PC21 and PC22, there are two different paths of tuning.

 Figure (C-1) Network topology diagram

The following figure (C-2) is the routing table of each router. It can be seen that the port IP and dynamic routing of each router have been configured.

Figure (C-2) routing table

Now that each port is open, let PC21 tracert 192.168.5.2 (PC22IP) in the command line, as shown in Figure (C-3), the routing path is 192.168.1.2->192.168.3.2->192.168.5.2, we It can be seen that the routing path is the one below, not the one above.

  Figure (C-3) Routing path when all ports are enabled

In the simulation mode, we can clearly see the path, and the path below is selected. As shown in the picture (C-4)

Figure (C-4) path in simulation mode with all ports enabled

If the E0/1/0 port of Route8 (IP address is 192.168.3.2) is disconnected, that is, the port is unavailable. As shown in the following figure (C-5), it can be seen from the topology diagram that there is no communication between the two ports. When also tracert 192.168.5.2 (IP of PC22) on the PC21 command line, the routing path is 192.168.1.2->192.168.2.2->192.168.4.2->192.168.5.2, that is, the routing path above is selected, you can It feels like routing is dynamically selected.

  Figure (C-5) The routing path of tracert192.168.5.2 after disconnecting a port

The following figure (C-6) is the PDU path, in which we can clearly see the path selection.

  Figure (C-6) PDU path after disconnecting a port

Task Three: Network Programming 

Programming requirements: capture the IP packets of the local network card , and analyze the captured IP packets. It is required to output the following fields: version number, total length, flag bit, slice offset, protocol, source address and destination address.

Detailed documentation is required, including program design ideas, workflow, key issues, program comments, and analysis screenshots of capture packages.

( Need to run as an administrator, debugging software Visual Studio2019 )

IP packet format:

(1) Detailed introduction of datagram and brief flow chart

  1. Version number: 4 digits in length, indicating the version of the IP protocol used. The value of the IPv4 version number field is 4; the value of the IPv6 version number field number is 6.
  2. Header length: The length is 4 bits, which defines the header length of an IP packet with a unit of 4B
  3. Service type: 8 bits in total, the upper 3 bits form the priority subfield, and the next 4 bits form the service type subfield.
  4. The total length of the datagram: the total length is 2B (that is, 6 bits). Defines the total length of the datagram in bytes.
  5. Reload ID: 16 bits in length, used to identify the number of the IP datagram, allowing the destination host to determine which group the new data belongs to.
  6. Fragmentation ID: 3 bits in total, the highest bit being 0; DF prohibits the fragmentation ID. DF=0, it can be fragmented; DF=1, it cannot be fragmented. MF: Fragment ID. MF=0 means that the last fragment is connected; MF=1 means it is not the last fragment.
  7. Fragment offset value: a total of 13 bits, indicating the relative position of the fragment in the entire datagram.
  8. Life cycle: 8 bits, used to set the lifetime of the data datagram during the entire network transmission. It is often controlled by the maximum number of router hops that a datagram can pass through.
  9. Protocol type: 8 bits in total, indicating the high-level protocol type of the IP datagram.
  10. Header checksum: a total of 16 bits, used to store the checksum for checking header errors.
  11. Source and host address: 32 bits in total, representing the IP addresses of the source host and the host that send and receive the datagram respectively.
  12. Option data field: 0-40B, used for control and test.

The flow chart is as follows (W-1)

 Figure (W-1) Brief Flowchart

(2) Definitions of some important parts:

 Structure of IP datagram 

struct IPheader {                         

	union {
		unsigned char banben;                     //IP数据报的版本(占4位)   
		unsigned char headlength;                 //IP数据报首部长度(占4位)
	};               

	unsigned char serviceType;                //IP数据报的区分服务(占8位) 
	unsigned short totallen;                  //总长度(16位)  
	unsigned short identifier;                //标识符  

	union {
		unsigned short Flags;                     //标志位 
		unsigned short FragOffset;                 //片偏移
	};             

	unsigned char TTL;                        //生存时间  
	unsigned char protocol;                   //协议   
	unsigned short checksum;                  //首部校验和  
	unsigned int sourceAddress;               //源IP地址  
	unsigned int destinAddress;               //目的IP地址    };  

 

Initialization of the dynamic                                  

WSADATA wsaData;                                        //存放windows socket初始化信息

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)     /初始化win socket网络库,申请2.2的版本

  //并判断是否初始化成功

{

int n= GetLastError();                       //用GetLastError函数获得错误代码

cout << "WSAStartup() failed:n" << n<< endl;  //初始化失败,报错并返回

return;

}

socket creation

SOCKET sock;
sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);               //调用socket函数来创建一个能够进行网络通信的套接字  
	if (sock == INVALID_SOCKET)                              //若套接字创建失败,则报错并返回。
	{
		int m = WSAGetLastError();
		cout << "WSASocket() failed:m" << m << endl;           //报错 
		return;
	}                                                //返回

	bool flag = TRUE;
	setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*)&flag, sizeof(flag)); //设置套接字的选项 

In the socket() function, the first parameter specifies the zone field where the communication takes place, and AF_INET is for the Internet, allowing communication between remote hosts. The second parameter is the type of socket. Under the AF_INET address family, there are three socket types: SOCK_STREAM, SOCK_DGRAM, and SOCK_RAW. Here, it is set to SOCK_RAW, indicating that a raw socket type is declared. The third parameter depends on the second parameter and is used to specify the specific protocol of the socket, here the IP protocol is used.  

Once a raw socket is created, the IP header is included in the received data. Then, you can set the IP header operation options, calling the setsockopt function. The flag is set to true, and the IP_HDRINCL option is set, indicating that the user can personally process the IP header.

Bind local machine address:

gethostname(hostName, 100);                     //获取本地主机名   
	ComIP = gethostbyname(hostName);            //获取本机IP地址   
	sockaddr_in host_addr;                      //存储ip信息,必须是网络字节的顺序  
	host_addr.sin_family = AF_INET;             //协议族   
	host_addr.sin_port = htons(6000);           //honts函数可以将主机数据转换为网络字节顺序的数据  
	host_addr.sin_addr = *(in_addr*)ComIP->h_addr_list[0];   
bind(sock, (PSOCKADDR)&host_addr, sizeof(host_addr));//把原始Socket绑定到本地网卡  
}

The bind() function provided by WinSock is used to bind a socket with an address. After binding, the raw socket can receive all IP data packets flowing through the network interface to which the IP address belongs.

Set the NIC to promiscuous mode:

DWORD dwValue = 1;
	DWORD dwBufferLen[10];
	DWORD dwBufferInLen = 1;
	DWORD dwBytesReturned = 0;
	WSAIoctl(sock, _WSAIOW(IOC_VENDOR, 1), &dwBufferInLen, sizeof(dwBufferInLen), &dwBufferLen, sizeof(dwBufferLen), &dwBytesReturned, NULL, NULL);

Capture and parse IP datagrams

void Print_stroe(int packsum)//循环捕获packnum个数据包,并解析输出
{
	int num = 0;
	while (num < packsum)
	{
		int n_recv = recv(sock, buffer, sizeof(buffer), 0);
		if (n_recv > 0)
		{
			cout << "--------------第" << ++num << "个数据包-------------- " << endl;
			IPheader ip = *(IPheader*)buffer;
			cout << "版本号: IPv" << (ip.banben >> 4) << endl;
			cout << "总长度: " << ip.totallen << endl;
			cout << "标志位: " << "DF=" << ((ip.Flags >> 14) & 0x01) << ", MF=" << ((ip.Flags >> 13) & 0x01) << endl;
			cout << "片偏移: " << (ip.FragOffset & 0x1fff) << " bits" << endl;
			cout << "协议: " << Getip(ip) << endl;
			cout << "原地址:" << inet_ntoa(*(in_addr*)&ip.sourceAddress) << endl;
			cout << "目的地址:" << inet_ntoa(*(in_addr*)&ip.destinAddress) << endl;
		}

	}
}

If the protocol type in the received data packet matches the defined raw socket, then the received datagram will be copied to the socket. Therefore, the network card can receive all IP data packets passing through the local network card. In this program, the recv() function is used to receive passing IP packets, and its parameters are socket descriptor, buffer address, and buffer size. In the program, the recv() function can be used to receive the passing IP packets. This function has four parameters, the first parameter is the socket descriptor used by the receiving operation; the second parameter is the address of the receiving buffer; the third parameter is the size of the receiving buffer, that is, the number of bytes to be received; The fourth parameter is an additional flag, if there is no special requirement for the sent data, set it to 0 directly. Because the maximum length of an IP packet is 65535 bytes, the size of the buffer cannot be smaller than 65535 bytes. After the buffer is set, the loop can be used to repeatedly monitor and receive IP packets.

(3) Debugging and running

The following figures (W-2) and (W-3) are the running screenshots of capturing 6 and 2 datagrams respectively.

Figure (W-2) captures 6 IP datagrams

 

Figure (W-3) captures 2 IP datagrams

(4) The source code is as follows:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream> 
#include<string> 
#include<stdio.h> 
#include<Winsock2.h>  
#include<ws2tcpip.h>  
#include<sys/types.h> 
#pragma comment(lib,"ws2_32.lib")  
using namespace std;
SOCKET sock;
char hostName[128];                        //主机名 
char buffer[65535];                        //缓冲区 
hostent* ComIP;                            //用于保存本机IP地址 

struct IPheader {                          //IP数据报的结构 

	union {
		unsigned char banben;                     //IP数据报的版本(占4位)   
		unsigned char headlength;
	};              //IP数据报首部长度(占4位) 

	unsigned char serviceType;                //IP数据报的区分服务(占8位) 
	unsigned short totallen;                  //总长度(16位)  
	unsigned short identifier;                //标识符  

	union {
		unsigned short Flags;                     //标志位 
		unsigned short FragOffset;
	};             //片偏移

	unsigned char TTL;                        //生存时间  
	unsigned char protocol;                   //协议   
	unsigned short checksum;                  //首部校验和  
	unsigned int sourceAddress;               //源IP地址  
	unsigned int destinAddress;
};             //目的IP地址    

void Start()                                //创建Socket 
{
	WSADATA wsaData;                                        //存放windows socket初始化信息 
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)           //初始化win socket网络库,申请2.2的版本,
															 //并判断是否初始化成功
	{
		int n= GetLastError();                               //用GetLastError函数获得错误代码
		cout << "WSAStartup() failed:n" << n<< endl;             //初始化失败,报错并返回
		return;
	}

	sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);            //调用socket函数来创建一个能够进行网络通信的套接字  
	if (sock == INVALID_SOCKET)                              //若套接字创建失败,则报错并返回。
	{
		int m = WSAGetLastError();
		cout << "WSASocket() failed:m" << m << endl;           //报错 
		return;
	}                                                //返回

	bool flag = TRUE;
	setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*)&flag, sizeof(flag)); //设置套接字的选项 
}


void Fill()//填充sockaddr_in并绑定socket 
{
	gethostname(hostName, 100);                  //获取本地主机名   
	ComIP = gethostbyname(hostName);            //获取本机IP地址   
	sockaddr_in host_addr;                      //存储ip信息,必须是网络字节的顺序  
	host_addr.sin_family = AF_INET;             //协议族   
	host_addr.sin_port = htons(6000);           //honts函数可以将主机数据转换为网络字节顺序的数据  
	host_addr.sin_addr = *(in_addr*)ComIP->h_addr_list[0];   bind(sock, (PSOCKADDR)&host_addr, sizeof(host_addr));//把原始Socket绑定到本地网卡  
}

void Set()//设置为混杂模式,截获流经网卡的所有IP数据报 
{
	DWORD dwValue = 1;
	DWORD dwBufferLen[10];
	DWORD dwBufferInLen = 1;
	DWORD dwBytesReturned = 0;
	WSAIoctl(sock, _WSAIOW(IOC_VENDOR, 1), &dwBufferInLen, sizeof(dwBufferInLen), &dwBufferLen, sizeof(dwBufferLen), &dwBytesReturned, NULL, NULL);
}

string Getip(IPheader ip)//根据IP头部信息返回相应协议类型字符串 
{
	int m = ip.protocol;
	switch (ip.protocol)
	{
	case 1:     return "ICMP"; //Internet控制报文协议 
	case 2:   return "IGMP"; //Internet组管理协议  
	case 4:   return "IPinIP";//移动IP数据封装和隧道  
	case 6:   return "TCP";//传输控制协议  
	case 8:   return "EGP";//外部网关协议  
	case 17:   return "UDP";//用户数据报文协议  
	case 41:   return "IPv6";
	case 46:   return "RSVP";//资源预留协议  
	case 89:   return "OSPF";// 开发式最短路径优先  
	default:    return "UNKNOW";
	}
}


void Print_stroe(int packsum)//循环捕获packnum个数据包,并解析输出
{
	int num = 0;
	while (num < packsum)
	{
		int n_recv = recv(sock, buffer, sizeof(buffer), 0);
		if (n_recv > 0)
		{
			cout << "--------------第" << ++num << "个数据包-------------- " << endl;
			IPheader ip = *(IPheader*)buffer;
			cout << "版本号: IPv" << (ip.banben >> 4) << endl;
			cout << "总长度: " << ip.totallen << endl;
			cout << "标志位: " << "DF=" << ((ip.Flags >> 14) & 0x01) << ", MF=" << ((ip.Flags >> 13) & 0x01) << endl;
			cout << "片偏移: " << (ip.FragOffset & 0x1fff) << " bits" << endl;
			cout << "协议: " << Getip(ip) << endl;
			cout << "原地址:" << inet_ntoa(*(in_addr*)&ip.sourceAddress) << endl;
			cout << "目的地址:" << inet_ntoa(*(in_addr*)&ip.destinAddress) << endl;
		}

	}
}



int main() {
	Start();                              //创建Socket 
	Fill();                               //填充sockaddr_in并绑定socket   
	Set();                               //设置为混杂模式,截获流经网卡的所有IP数据报  
	cout << "请输入要捕获的IP包数目:" << endl;
	int packsum;
	cin >> packsum;//输入需要解析的IP包数目  
	cout << "开始捕获并分析IP数据包" << endl;
	cout << endl;
	Print_stroe(packsum);//循环捕获packnum个数据包  
	closesocket(sock);//关闭socket  
	WSACleanup();//关闭winsock   
	return 1;
}
  

  • Curriculum Design Summary Experience

(1) command

1. The arp command took a lot of time, because adding static IP addresses and physical addresses and deleting them needs to be run in administrator mode. It took a long time to find out that this is the case, and finally found out by consulting online information.

2. The tracert command, in addition to its own address, is more difficult to find an available IP address. It's hard to find anything other than baidu.

3. Telnet command: At the beginning, no configuration was changed, so I entered telnet on the command line, and found that there was no such command. After searching the information on the Internet, I found that this command needs to enable the telnet client function in the "Enable and Disable Windows Function". After checking and confirming, I found that typing telnet on the command line can enter this command, but because there is no open port, any operation will fail. At first, I didn't know that it was necessary to enter a port to realize the operation of some commands. I thought it was a problem with the computer configuration. After tossing and turning for a long time, there was no gain, but it was finally completed under the guidance of a correct step. I just learned that the opened port number can be checked by typing netstat -a -n in the command line, and finally you can enter the port, and after entering the port, press "CTRL+]" to realize the operation. This should be the most time-consuming command. At the same time, during the implementation of this command, I also roughly understood some conditions and problems of remote connections, which is still very meaningful.

(2) Simulation experiment:

The command of static routing took a lot of time, because the title requires four routers, the connection between routers and the connection between routers and switches are different, and there are many port IPs and subnet masks that need to be configured during the configuration process. Hosts and ports in different locations need to be configured with IPs according to the routers they are connected to. After setting these, you need to configure the next hop in the command line. I don’t know what’s wrong. After the initial configuration, show ip rou on the router will not always display the configured next hop information. This means that the configuration is unsuccessful, and the specific reason has not been found. I have repeated the configuration for a long time here, and I don't know what went wrong. But later, after changing the PC, switch and router, it was configured again, and it was found that the configuration was successful, and finally the next step can be carried out. After the configuration, I found that it is not possible to configure in the command line in the console, or you can directly view the properties and configure, but configuring in the console can better exercise and cultivate your own abilities.

Dynamic routing configuration is not so difficult, but two different routes need to be planned to show the difference between dynamic and static.

But you also need to plan the IP address of the interface and PC.

(3) Network programming

Guess you like

Origin blog.csdn.net/cangzhexingxing/article/details/125091310