Windows UDP単純インスタンス

2985 ワード

直接上例コード
client:
#include 
#include 

#pragma comment(lib,"ws2_32.lib")
#define	BUF_SIZE	1024
#define PORT_		9411

int main(void)
{
	WSADATA wsd;
	int iRet = 0;

	//          
	if(WSAStartup(MAKEWORD(2,2), &wsd) != 0){
		iRet = WSAGetLastError();
		printf("WSAStartup failed !
"); return -1; } char strSend[BUF_SIZE] = "test udp send", strRecv[BUF_SIZE] = {0}; SOCKADDR_IN servAddr; SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); // servAddr.sin_family = AF_INET; //servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.0.104"); servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.0.255"); servAddr.sin_port = htons(PORT_); // int nServAddLen = sizeof(servAddr); iRet = sendto(sockClient, strSend, BUF_SIZE, 0, (sockaddr *)&servAddr, nServAddLen); if(iRet == SOCKET_ERROR){ printf("sendto() failed:%d
", WSAGetLastError()); closesocket(sockClient); WSACleanup(); return -1; } iRet = recvfrom(sockClient, strRecv, BUF_SIZE, 0, (sockaddr *)&servAddr, &nServAddLen); if(SOCKET_ERROR == iRet) { printf("recvfrom failed:%d
", WSAGetLastError()); closesocket(sockClient); WSACleanup(); return -1; } printf("Recv From Server:%s
", strRecv); closesocket(sockClient); WSACleanup(); return 0; }

server:
#include 
#include 

#pragma comment(lib,"ws2_32.lib")
#define	BUF_SIZE	1024
#define PORT_		9411

int main(void)
{
	WSADATA wsd;
	int iRet = 0;

	//          
	if(WSAStartup(MAKEWORD(2,2), &wsd)!= 0){
		printf("WSAStartup failed:%d!
", WSAGetLastError()); return -1; } SOCKET socketSrv = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); SOCKADDR_IN addrSrv; SOCKADDR_IN addrClient; char strRecv[BUF_SIZE] = {0}, strSend[BUF_SIZE] = "udp server send"; int len = sizeof(SOCKADDR); // ZeroMemory(strRecv,BUF_SIZE); //addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_addr.S_un.S_addr = inet_addr("192.168.0.104"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(PORT_); // iRet = bind(socketSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); if(SOCKET_ERROR == iRet) { printf("bind failed%d!
", WSAGetLastError()); closesocket(socketSrv); WSACleanup(); } // printf("udp server start...
"); while(TRUE) { iRet = recvfrom(socketSrv,strRecv,BUF_SIZE,0,(SOCKADDR*)&addrClient,&len); if(SOCKET_ERROR == iRet){ printf("recvfrom failed !
"); closesocket(socketSrv); WSACleanup(); return -1; } printf("Recv From Client:%s
", strRecv); // sendto(socketSrv, strSend, sizeof(strSend), 0, (SOCKADDR*)&addrClient, len); } closesocket(socketSrv); WSACleanup(); return 0; }