網路程式設計 UDP

2021-08-11 00:22:46 字數 2448 閱讀 6130

一、udp協議

1、udp協議:udp與tcp一樣,都屬於運輸層協議,udp為應用層提供不可靠、無連線的、基於資料報的服務。

2、udp報頭

3、udp與tcp的比較

tcp : 它是一種面向連線的,可靠的,流式服務。

udp:它是一種無連線的,不可靠的,資料報服務

tcp的「可靠」:tcp協議使用超時重傳、資料確認等方式來確保資料報被正確地傳送至目的端,因此tcp是可靠的。

udp的「不可靠」:udp協議無法保證資料從傳送端正確的傳送到目的端。如果資料在中途丟失,或者目的端通過資料校驗發現資料錯誤而將其丟棄,則udp協議只是簡單的通知應用程式傳送失敗。因此,udp協議的應用程式通常要自己處理資料確認、超時重傳等邏輯。

流式服務

資料報服務

二、使用udp協議完成網路程式設計

1、協議選擇(本篇部落格選擇udp)

tcp協議:它是一種面向連線的,可靠的,流式服務。

udp協議:它是一種無連線,不可靠的,資料報服務。

2、udp的程式設計流程:

ser(伺服器端):socket、 bind、 recvfrom/sendto、 close

cli(客戶端):socket、 sendto/recvfrom、 close

接下來說一下用到的函式(socket與close在這裡就不介紹了)

a. int recvfrom(int sockfd, void buff, int len, int flag, struct sockaddr *src_addr, int addr_len);

buff:指定緩衝區的位置

len:指定緩衝區的大小

src_addr:傳送端的socket位址

addr_len:傳送端socket位址的長度

b. int sendto(int sockfd, void *buff, int len, int flag, struct sockaddr*dest_addr, int addr_len);

buff:指定緩衝區的位置

len:指定緩衝區的大小

dest_addr:接收端的socket位址

addr_len:接收端socket位址的長度

**實現

ser.c

#include 

#include

#include

#include

#include

#include

#include

#include

int main()

; int len = sizeof(cli);

recvfrom(sockfd,buff,127,0,(struct sockaddr*)&cli,&len);

printf("ip::%s\nport::%d\ndata::%s\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port),buff);

sendto(sockfd,"i know",sizeof("i know"),0,(struct sockaddr*)&cli,len);

}close(sockfd);

return

0;}

cli.c

#include 

#include

#include

#include

#include

#include

#include

#include

int main()

; printf("buff\n");

sendto(sockfd,"hello world!",sizeof("hello world!"),0,(struct sockaddr*)&ser,sizeof(ser));

sendto(sockfd,"hello world!",sizeof("hello world!"),0,(struct sockaddr*)&ser,sizeof(ser));

recvfrom(sockfd,buff,127,0,null,null);

printf("%s\n",buff);

close(sockfd);

return

0;}

執行結果

UDP網路程式設計

基於udp 伺服器 程式步驟 1.建立乙個socket,用socket 函式 2.繫結ip位址 埠等資訊到socket上,用函式bind 3.迴圈接收資料,用recvfrom 4.關閉網路連線。基於udp 客戶端 程式步驟 1.建立乙個socket,用socket 函式 2.繫結ip位址 埠等資訊到...

UDP網路程式設計

基於udp 通訊模型 由上圖可以看出udp通訊的步驟如下 基於udp 伺服器 1 建立乙個socket,用函式socket 2 繫結ip位址 埠等資訊到socket上,用函式bind 3 迴圈接收資料,用函式recvfrom 4 關閉網路連線 基於udp 客戶端 1 建立乙個socket,用函式so...

網路程式設計 UDP

網路程式設計傳輸層選擇乙個資料控制模式 tcp或者udp,前面我們已經介紹了tcp程式設計,這篇我們簡單的來看看udp程式設計。udp是無連線的不可靠的資料報服務。udp協議在ip協議上增加了復用 分用和差錯檢測功能。udp的特點 a 是無連線的。相比於tcp協議,udp協議在傳送資料前不需要建立連...