乙個簡單的UDP廣播例子 含C S

2021-06-06 16:04:35 字數 1980 閱讀 9396

乙個簡單的udp廣播通訊的例子程式,含有服務端和客戶端的**。

// 服務端  

//

#include "stdafx.h"

#include #include #pragma comment(lib, "ws2_32.lib")

int _tmain(int argc, _tchar* argv)

if(2 != hibyte(wsadata.wversion) || 2 != lobyte(wsadata.wversion))

socket sock = socket(af_inet, sock_dgram, ipproto_udp);

if(invalid_socket == sock)

sockaddr_in addr;

memset(&addr, 0, sizeof(addr));

addr.sin_family = af_inet;

addr.sin_addr.s_un.s_addr = htonl(inaddr_broadcast);

addr.sin_port = htons(5150);

bool bboardcast = true;

if(socket_error == setsockopt(sock, sol_socket, so_broadcast, (char*)&bboardcast, sizeof(bboardcast)))

wsacleanup();

} printf("server start, start to boardcast .../n");

char buf = ;

while(true)

sleep(1000);

} wsacleanup();

return 0;

}

// 客戶端  

//

#include "stdafx.h"

#include #include #pragma comment(lib, "ws2_32.lib")

int _tmain(int argc, _tchar* argv)

if(2 != hibyte(wsadata.wversion) || 2 != lobyte(wsadata.wversion))

socket sock = socket(af_inet, sock_dgram, ipproto_udp);

if(invalid_socket == sock)

sockaddr_in addr;

memset(&addr, 0, sizeof(addr));

addr.sin_family = af_inet;

addr.sin_addr.s_un.s_addr = htonl(inaddr_any);

addr.sin_port = htons(5150);

if(socket_error == bind(sock, (lpsockaddr)&addr, sizeof(addr)))

wsacleanup();

return exit_failure;

} #define max_buffer 256

char szbuf[max_buffer] = ;

sockaddr_in remote;

memset(&remote, 0, sizeof(remote));

int len = sizeof(remote);

while(true)

printf("recv data: <%s : %d> %s/n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port), szbuf);

} return 0;

}

乙個簡單的UDP廣播程式

一般使用的socket程式設計都是使用的是一些繫結埠和ip的普通的程式,一旦想要編寫一些特殊的網路應用程式就會出現一些問題。就那這個udp廣播資料的車姑娘許來說,需要設定socket的選項,也就是使用setsockopt來設定socket的一些特殊選項。include include include...

乙個簡單基於UDP的回顯C S 一

問題 伺服器端意外崩潰或重啟,客戶端不得而知 特點 迭代伺服器 服務端 vi s4.c include include include include include include include define serv port 9877 define maxline 4096 void ser...

乙個基於UDP的回顯C S 二

解決問題 通過connect,使伺服器端意外崩潰,重啟,客戶端能通過read函式而得知 伺服器端 vi s4.c include include include include include include include define serv port 9877 define maxline ...