一个简单的udp接收数据的例子

 

#include <winsock2.h>

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

#include <stdio.h>

void main()

{

WSADATA wsaData;

WSAStartup(MAKEWORD(2, 2), &wsaData);

SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

SOCKADDR_IN LocalAddr;

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

LocalAddr.sin_family = AF_INET;

LocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);

LocalAddr.sin_port = htons(1234);

bind(sock, (LPSOCKADDR) &LocalAddr, sizeof(LocalAddr));

while (1)

{

char echo[100]="";

SOCKADDR_IN from;

ZeroMemory(&from, sizeof(from));

int fromlen = sizeof(from);

int n = recvfrom(sock, echo, 100, 0, (SOCKADDR *)&from, &fromlen);

if (n != SOCKET_ERROR) {

echo[n] = '\0';

printf("%d bytes received. echoes \"%s\"", n, echo);

}

}

closesocket(sock);

WSACleanup();

}

你可能感兴趣的:(socket,include)