这里列出了两种方法,第一种是不指定本地端口号和ip,第二种是指定本地端口号和ip。首选第二种。
方法一:
#include <stdio.h>
#include <WinSock2.h>
int main()
{
printf("发送方:\n");
SOCKET sock;
sockaddr_in remote;
int addr_len = sizeof(sockaddr_in);
char buf[128];
int len = 0;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
printf("create socket failed!\n");
return -1;
}
remote.sin_family = AF_INET;
remote.sin_port = htons(9001);
remote.sin_addr.s_addr = inet_addr("127.0.0.1");
while (1)
{
memset(buf, 0, 128);
sprintf_s(buf, "%s", "hello");
len = 5;
sendto(sock, buf, len, 0, (struct sockaddr*)&remote, addr_len);
system("pause");
}
closesocket(sock);
return 0;
}
方法二:
#include <stdio.h>
#include <WinSock2.h>
int main()
{
printf("发送方:port=9000 ...\n");
SOCKET sock;
sockaddr_in local;
sockaddr_in remote;
char buf[128];
int len = 0;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
printf("create socket failed!\n");
return -1;
}
local.sin_family = AF_INET;
local.sin_port = htons(9000);
local.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(sock, (sockaddr*)&local, sizeof(sockaddr_in)) < 0)
{
printf("binding socket failed!\n");
return -1;
}
remote.sin_family = AF_INET;
remote.sin_port = htons(9001);
remote.sin_addr.s_addr = inet_addr("127.0.0.1");
while (1)
{
memset(buf, 0, 128);
sprintf_s(buf, "%s", "hello");
len = 5;
sendto(sock, buf, len, 0, (struct sockaddr*)&remote, sizeof(sockaddr_in));
system("pause");
}
closesocket(sock);
return 0;
}