服务器:
#include <iostream>
#ifdef WIN32
#include <Windows.h>
#define socklen_t int
#else
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#define closesocket close
#endif
using namespace std;
int main(int argc, char* argv[])
{
unsigned short port = 8080;
if (argc > 1)
{
port = atoi(argv[1]);
}
//win中的初始化
#ifdef WIN32
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
#endif
//创建UDP类型的socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock <= 0)
{
cout << "create udp socket failed" << endl;
return -1;
}
cout <<"sock:"<<sock << endl;
//绑定端口
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = htonl(0);
if (::bind(sock, (sockaddr*)&saddr, sizeof(saddr)) != 0)
{
cout << "bind port failed" << endl;
return -2;
}
cout << "bind port "<<port<<" success" << endl;
//监听
listen(sock, 10);
//接收
sockaddr_in cli_saddr;
socklen_t len = sizeof(cli_saddr);
char* buf = new char[10240];
int re = recvfrom(sock, buf, sizeof(buf), 0, (sockaddr*)&cli_saddr,&len);
if (re < 0)
{
cout << "recvfrom failed" << endl;
return -3;
}
buf[re] = '\0';
cout << buf << endl;
//打印ip和端口信息
cout << "recv:" << inet_ntoa(cli_saddr.sin_addr) << ntohs(cli_saddr.sin_port) << endl;
//回复
sendto(sock, "67890", 6,0, (sockaddr*)&cli_saddr, sizeof(cli_saddr));
closesocket(sock);
delete[] buf;
system("pause");
return 0;
}
客户端:
#include <iostream>
#ifdef WIN32
#include <Windows.h>
#else
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#define closesocket close
#endif
using namespace std;
int main(int argc, char* argv[])
{
unsigned short port = 8080;
if (argc > 1)
{
port = atoi(argv[1]);
}
#ifdef WIN32
//win中的初始化
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
#endif
//创建UDP类型的socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock <= 0)
{
cout << "create udp socket failed" << endl;
return -1;
}
cout << "create udp client socket success" << endl;
//发送
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int len = sendto(sock, "12345", 6, 0, (sockaddr*)&saddr, sizeof(saddr));
cout << "sento size is " << len << endl;
//接收
char* recvbuf = new char[1024];
recvfrom(sock,recvbuf,sizeof(recvbuf),0,0,0 );
cout << recvbuf << endl;
//
closesocket(sock);
delete[] recvbuf;
system("pause");
return 0;
}