資源簡介
應用libnet庫發送自定義的tcp和udp數據包
## 安裝libnet
cd /home
tar -zxvf libnet-1.2-rc3.tar.gz
cd libnet-1.2-rc3
./configure --prefix=/usr
make
make install
cd /home
代碼片段和文件信息
//讀文件tcp6.cpp
#include??
#include?
#include?//ifstream讀文件,ofstream寫文件,fstream讀寫文件
#include
#include?//文本對象,儲存讀取的內容
#include?//屏幕輸出cout
#include?//調用system(“pause“);
using?namespace?std;
#include?
#define?SIZE?1024
typedef?struct
{
????char?yip[30];
????char?mip[30];
????int??yport;
????int??mport;
????char?xieyi[20];
????char??paylo[255];
}student;
student?stu[SIZE]?buf[SIZE];
int?main()?{
????ifstream?in(“1.txt“);
????string?line;
????int?i?=?0;
????int?num?=?0;
????if?(in)?//?有該文件
????{
????????while?(getline(in?line))?//?line中不包括每行的換行符
????????{
????
????????????istringstream?is(line);
????????????string?str0?str1?str2?str3?str4str5;
????????????is?>>?str0?>>?str1?>>?str2?>>?str3?>>?str4?>>?str5;
????????????//cout?<????????????strcpy(buf[i].yip?str0.c_str());
????????????strcpy(buf[i].mip?str1.c_str());
????????????buf[i].yport?=?atoi(str2.c_str());
????????????buf[i].mport?=?atoi(str3.c_str());
????????????strcpy(buf[i].xieyi?str4.c_str());
????????????strcpy(buf[i].paylo?str5.c_str());
????????????i++;
????????????num++;
????????}
????}
????else?//?沒有該文件
????{
????????cout?<“no?such?file“?<????}
????i?=?0;
????while?(num>=0)?{
????????char?xie[20]=“TCP“;
???????//?cout< ????????if(strcmp?(buf[i].xieyixie)?==?0){
????????libnet_t*?handle;?/*?Libnet句柄?*/
????????int?packet_size;?/*?構造的數據包大小?*/
????????char*?device?=?“eno1“;?/*?設備名字也支持點十進制的IP地址會自己找到匹配的設備?*/
????????char*?src_ip_str?=?buf[i].yip;?/*?源IP地址字符串?*/
????????char*?dst_ip_str?=?buf[i].mip;?/*?目的IP地址字符串?*/
????????u_char?src_mac[6]?=?{?0x0c0xc40x7a0x770x3d0x62?};?/*?源MAC?*/
????????u_char?dst_mac[6]?=?{?0x0c0xc40x7a0x770x3d0x2e?};?/*?目的MAC?*/
????????u_long?dst_ip?src_ip;?/*?網路序的目的IP和源IP?*/
????????char?error[LIBNET_ERRBUF_SIZE];?/*?出錯信息?*/
????????libnet_ptag_t?eth_tag?ip_tag?tcp_tag?tcp_op_tag;?/*?各層build函數返回值?*/
????????u_short?proto?=?IPPROTO_TCP;?/*?傳輸層協議?*/
????????char?payload[255]?=?{?0?};?/*?承載數據的數組,初值為空?*/
????????u_long?payload_s?=?0;?/*?承載數據的長度,初值為0?*/
????????/*?把目的IP地址字符串轉化成網絡序?*/
????????dst_ip?=?libnet_name2addr4(handle?dst_ip_str?LIBNET_RESOLVE);
????????/*?把源IP地址字符串轉化成網絡序?*/
????????src_ip?=?libnet_name2addr4(handle?src_ip_str?LIBNET_RESOLVE);
????????/*?初始化Libnet?*/
????????if?((handle?=?libnet_init(LIBNET_link?device?error))?==?NULL)?{
????????????printf(“libnet_init?failure\n“);
????????????return?(-1);
????????};
????????strncpy(payload?buf[i].paylo?sizeof(payload)?-?1);?/*?構造負載的內容?*/
????????payload_s?=?strlen(p
- 上一篇:FTP客戶端源碼(c++)
- 下一篇:modbus tcp/ip 簡單通訊
評論
共有 條評論