Linux network programming technology of raw socket programming

Linux background development 2020-11-11 14:38:32
linux network programming technology raw


Raw socket programming and before UDP Programming is almost , After creating a socket , Receive data or send data through this socket . The difference lies in , The raw socket can self assemble packets ( Camouflage local IP, Local MAC), It can receive all the data frames on the local network card ( Data packets ). in addition , You must have administrator privileges to use raw sockets .

The creation of the original socket

int socket ( int family, int type, int protocol );

Parameters :

  • family: Protocol family Write here PF_PACKET
  • type: Socket class , Write here SOCK_RAW
  • protocol: Type of agreement , Specifies the type of packet that can be received or sent , Can't write “0”, The values are as follows , Be careful , You need to use htons() Do byte order conversion .
  • ETH_P_IP:IPV4 Data packets
  • ETH_P_ARP:ARP Data packets
  • ETH_P_ALL: Packets of any protocol type

Return value :

 success ( >0 ): Socket , Here is the socket of the link layer
Failure ( <0 ): error 

need C/C++ Linux Server architect learning materials plus group 812855908( The information includes C/C++,Linux,golang technology ,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK, Streaming media ,CDN,P2P,K8S,Docker,TCP/IP, coroutines ,DPDK,ffmpeg etc. )

Linux Network programming technology of the original socket programming details

Examples are as follows :

// Required header file
#include <sys/socket.h>
#include <netinet/ether.h>
#include <stdio.h> // perror
int main(int argc,char *argv[]) {
int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL) );
if(sock_raw_fd < 0){
perror("socket");
return -1;
}
return 0;
}

Get the data packet of link layer

ssize_t recvfrom( int sockfd,

void *buf,

size_t nbytes,

int flags,

struct sockaddr *from,

socklen_t *addrlen );

Parameters :

  • sockfd: Raw socket
  • buf: Receive data buffer
  • nbytes: The size of the receive data buffer
  • flags: Socket flag ( Often 0)
  • from: It's not useful here , Write NULL
  • addrlen: It's not useful here , Write NULL

Return value :

 success : Number of characters received
Failure :-1

Examples are as follows :

#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/ether.h>
int main(int argc,char *argv[]) {
unsigned char buf[1024] = {0};
int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
// Get the data packet of link layer
int len = recvfrom(sock_raw_fd, buf, sizeof(buf), 0, NULL, NULL);
printf("len = %dn", len);
return 0;
}

Hybrid mode

By default , We receive data , The destination address is a local address , Will receive . Sometimes we want to receive all the data streams that pass through the network card , Whether or not the destination address is it , At this time, we need to set the network card to hybrid mode .

The hybrid mode of network card is usually used by network administrator when analyzing network data as a means of network fault diagnosis , At the same time, this mode is also used by network hackers as the entrance of network data eavesdropping . stay Linux When setting network card hybrid mode in the operating system, administrator's permission is required . stay Windows Operating system and Linux The operating system has the use of hybrid mode packet capture tools , Like the famous open source software Wireshark.

By order to Linux Network card set hybrid mode ( Administrator privileges required )

Set hybrid mode :ifconfig eth0 promisc

Linux Network programming technology of the original socket programming details

Cancel hybrid mode :ifconfig eth0 -promisc

Linux Network programming technology of the original socket programming details

Give to by code Linux Network card set hybrid mode

Linux Network programming technology of the original socket programming details

The code is as follows :

struct ifreq req; // Network interface address
strncpy(req.ifr_name, "eth0", IFNAMSIZ); // Specify the network card name
if(-1 == ioctl(sock_raw_fd, SIOCGIFINDEX, &req)) // Get the network interface
{
perror("ioctl");
close(sock_raw_fd);
exit(-1);
}
req.ifr_flags |= IFF_PROMISC;
if(-1 == ioctl(sock_raw_fd, SIOCSIFINDEX, &req)) // Network card set hybrid mode
{
perror("ioctl");
close(sock_raw_fd);
exit(-1);
}

Send custom packets :

ssize_t sendto( int sockfd,

const void *buf,

size_t nbytes,int flags,

const struct sockaddr *to,

socklen_t addrlen );

Parameters :

  • sockfd: Raw socket
  • buf: Send data buffer
  • nbytes: The size of the send data buffer
  • flags: It's usually 0
  • to: Local network interface , It refers to the network card from which the data should be sent out , Instead of the previous destination address
  • addrlen:to The length of the pointed content

Return value :

 success : Number of characters to send data
Failure : -1

Definition of native network interface

Linux Network programming technology of the original socket programming details

Send the complete code as follows :

struct sockaddr_ll sll; // Original socket address structure
struct ifreq req; // Network interface address
strncpy(req.ifr_name, "eth0", IFNAMSIZ); // Specify the network card name
if(-1 == ioctl(sock_raw_fd, SIOCGIFINDEX, &req)) // Get the network interface
{
perror("ioctl");
close(sock_raw_fd);
exit(-1);
}
/* Assign the network interface to the original socket address structure */
bzero(&sll, sizeof(sll));
sll.sll_ifindex = req.ifr_ifindex;
// send data
// send_msg, msg_len There is no definition here , Simulate
int len = sendto(sock_raw_fd, send_msg, msg_len, 0 , (struct sockaddr *)&sll, sizeof(sll));
if(len == -1)
{
perror("sendto");
}

Here the header file is as follows :

#include <net/if.h>// struct ifreq
#include <sys/ioctl.h> // ioctl、SIOCGIFADDR
#include <sys/socket.h> // socket
#include <netinet/ether.h> // ETH_P_ALL
#include <netpacket/packet.h> // struct sockaddr_ll
版权声明
本文为[Linux background development]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云