1, this example uses a PC, there are two network ports, the OS is CentOS 6.8, and then use two network cables are connected to the same switch, when the data through the switch, the switch's data will blink, otherwise there is no data through the switch.
2, start testing, it is a matter of course to think of the TCP server/tcp client mode, set up a socket
int server_sockfd = socket (af_inet,sock_stream, 0); struct sockaddr_in server_sockaddr; server_sockaddr.sin_family = af_inet; server_sockaddr.sin_port = htons (MYPORT); &NBSP;&NBSP;SERVER_SOCKADDR.SIN_ADDR.S_ADDR&NBSP;=&NBSP;INET_ADDR (IP_PORT_0); if (Bind ( SERVER_SOCKFD, (struct sockaddr *) &server_sockaddr,sizeof (server_sockaddr)) ==-1) { perror ("bind"); exit (1); } if (Listen (Server_sockfd,queue) == -1) { perror ("Listen"); exit (1); } char buffer[buffer_size]; struct sockaddr_in client_addr; socklen_t length = sizeof (CLIENT_ADDR); int conn = accept (server_sockfd, (struct sockaddr*) &client_addr, &length) if (conn<0) { perror ("Connect"); exit (1); } while (1) { memset (buffer,0,sizeof (buffer)); &NBSP;&NBSP;INT&NBSP;LEN&NBSP;=&NBSP;RECV (conn, buffer, sizeof (buffer), 0); send (conn, buffer, len, 0); } close (conn); close (SERVER_SOCKFD); return 0;}
The TCP client side also writes the corresponding code, compiles through, successively executes the Server/client program, the display has the data to send and receive the success, but the switch data lamp does not have any display, therefore understood, the system defaults directly sends receives the data from the local, and did not actually send out from the network card port, Because TCP is based on IP protocols, and the IP protocol is sure to take local internal routes, protocols that use IP such as TCP,UDP will certainly not succeed.
int init_sock (Char index[ifnamsiz]) { int fd = socket (PF_PACKET, sock_raw, htons (Eth_p_all)); struct sockaddr_ll sll; struct ifreq ifr; strncpy (Ifr.ifr_name, index , ifnamsiz); ioctl (Fd, SIOCGIFINDEX, &NBSP;&IFR); bzero (&sll, sizeof (SLL)); sll.sll_ifindex = ifr.ifr_ifindex; ioctl (FD, &NBSP;SIOCGIFHWADDR,&NBSP;&IFR); memcpy (sll.sll_addr,ifr.ifr_hwaddr.sa_data,6 ); sll.sll_family&nbsP;= af_packet; sll.sll_protocol = htons (Eth_p_all); bind (FD, struct sockaddr *) &sll,sizeof (SLL)); return fd;}
After initializing with the raw socket as above, send receive again, everything ok!!! , can receive the complete link layer frame except CRC, including MAC address, frame Type field, etc., when the program sends and receives, the data lamp of the switch flashes continuously.
This article is from the "accumulate small stream into the river" blog, please make sure to keep this source http://laoxiong.blog.51cto.com/5735045/1880968
Using the C socket raw function to achieve data transmission between two network ports of the same host