c語言實現簡單的udp傳輸( c s 模型)

2021-06-28 07:27:22 字數 1351 閱讀 3294

客戶端**:

/*client.c*/

#include #include #include #include #include #include #define maxbuf 256

int main(int argc, char const *argv)

; /*解析引數*/

if (argc != 2)

bzero(&srv, sizeof(srv));

srv.sin_family = pf_inet;

srv.sin_addr.s_addr = inet_addr(argv[1]);

srv.sin_port = htons(port);

/*建立 udp 套節字*/

s = socket(af_inet, sock_dgram, 0);

if(s<0)

while(1)else

}}

伺服器端**:

/*server.c*/

#include #include #include #include #include #include #define maxbuf 256

int main(int argc, char const *argv)

; struct sockaddr_in addr, cli;

/*初始化本地監聽埠資訊*/

bzero(&addr, sizeof(addr));

addr.sin_family = pf_inet;

addr.sin_addr.s_addr = inaddr_any;

addr.sin_port = htons(port);

/*建立udp套節字*/

s = socket(af_inet, sock_dgram, 0);

if (s<0)

/*允許埠復用*/

setsockopt(s, sol_socket, so_reuseaddr, &reuse, sizeof(reuse));

/*繫結指定埠*/

if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)

while(1)else }

return 0;

}

編譯命令:

客戶端:

gcc client.c -o client

./client 127.0.0.1

服務端:

gcc server.c -o server

./server

Linux下C語言實現簡單的udp通訊

用c語言實現udp 通訊。寫乙個udp 的客戶端,可以向外傳送訊息。再寫乙個udp服務端,接收客戶端的訊息,並且列印出來。事先說明 在window和linux中有一下結構 struct sockaddr struct sockaddr in 在netinet in.h 中定義 儲存ip位址,使用in...

c語言實現廣播(udp協議)

使用udp實現廣播功能 當我們執行 時 file send 執行傳送廣播 file recv 執行接收廣播 預設埠為 9999 include include include include include include include intbroadcast send int port 2.開...

C語言實現簡單的HashTble

標頭檔案中的原始定義 ifndef helpsep h define mintablesize 1 typedef char elementtype struct listnode typedef struct listnode position struct hashtbl typedef str...