当前位置:文档之家› UDP协议代码

UDP协议代码

服务端

// server.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"

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

#include

#include

#include

#define MAX_BUF 65536

int _tmain(int argc, _TCHAR* argv[])

{ WSAData wsaData;

int err = WSAStartup(WINSOCK_VERSION,&wsaData);

if(0!=err){return -1;}

SOCKET sock;

sock = socket(AF_INET, SOCK_DGRAM, 0);

if(INV ALID_SOCKET==sock)

{printf("socket() Failed: %d\n",WSAGetLastError());

WSACleanup();return -1;}

sockaddr_in LocaAddr;

LocaAddr.sin_family = AF_INET;

LocaAddr.sin_port = htons(10000);

LocaAddr.sin_addr.s_addr=htonl(INADDR_ANY);

err = bind(sock, (sockaddr *)&LocaAddr, sizeof(LocaAddr));

if(SOCKET_ERROR==err) //出错处理

{printf("bind() Failed: %d\n",WSAGetLastError());

closesocket(sock);WSACleanup();return -1;}

char rbuf[MAX_BUF];

memset(rbuf, 0, MAX_BUF);

sockaddr_in RomoteAddr;

int RemoteLen = sizeof(RomoteAddr);

int rByte = recvfrom(sock, rbuf, MAX_BUF, 0, (sockaddr*)

&RomoteAddr, &RemoteLen);

if(SOCKET_ERROR==rByte) //出错处理

{printf("recvfrom() Failed: %d\n",WSAGetLastError());

closesocket(sock);WSACleanup();return -1;}

printf("UDP recv[%d]DATA from %s: %s\n", rByte, inet_ntoa

(RomoteAddr.sin_addr), rbuf);

intsByte=sendto(sock, rbuf, strlen(rbuf), 0,(sockaddr *)

&RomoteAddr, sizeof(RomoteAddr));

if(SOCKET_ERROR==sByte) //出错处理

{printf("sendto() Failed: %d\n",WSAGetLastError());

closesocket(sock);WSACleanup();return -1;}

closesocket(sock);WSACleanup();return 0;}

客户端

// client.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"

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

#include

#include

#include

int _tmain(int argc, _TCHAR* argv[])

{ 初始化

char b[100];

char data[] = "Hello World!";

char dest_ip[] = "127.0.0.1";

unsigned short dest_port=10000;

sockaddr_in RemoteAddr;

RemoteAddr.sin_family = AF_INET;

RemoteAddr.sin_port = htons(dest_port);

RemoteAddr.sin_addr.S_un.S_addr = inet_addr(dest_ip);

SOCKET sock;

sock=socket(AF_INET,SOCK_DGRAM,0);

if(INV ALID_SOCKET ==sock)

{printf("socket() Failed:%d\n",WSAGetLastError());

WSACleanup();return -1;}

int n = sendto(sock,data,strlen(data),0,(sockaddr *)&RemoteAddr,sizeof(RemoteAddr));

printf("sending data number :%d\n",n);

int m = recvfrom(sock,b,sizeof(b),0,NULL,NULL);

printf("the number of receiving data:%d\n",m);

b[m] = '\0';printf("receive data: %s\n",b);

closesocket(sock); WSACleanup();return 0;}

相关主题