作为试图围绕 udp 套接字的尝试,我尝试将代码从本教程页面http://www.linuxhowtos.org/C_C++/socket.htm移植到 winsock(如果重要,在 win 8 上运行)。[以下直接链接]
代码当前编译并运行,但我从未收到数据包,两个程序都只是等待并阻塞 recvfrom()。我一直遇到同样的问题(例如,使用包含 recvfrom() 调用的此代码的修改版本https://stackoverflow.com/a/679529/873217 。并且使用此代码C++ 问题与 Datagram (UDP)winsocket 到sendto 和 recvfrom 通过环回适配器在同一个套接字上进行建议的更改)。我想我犯了一些简单而根本的错误;但我无法自己找到它。希望有更多经验的人可以为我解决这个问题。谢谢。
附加说明:
我在同一台计算机上运行服务器 exe,然后运行客户端 exe。它连接到互联网。我也尝试过使用解析为我的 IP 地址的域。我也尝试过禁用防火墙,尽管我已经允许两个程序完全访问。
直接链接到原始客户端和服务器代码:
http ://www.linuxhowtos.org/data/6/client_udp.c
http://www.linuxhowtos.org/data/6/server_udp.c
我目前的尝试:
都链接到 libws2_32.a
客户端代码:
#include <stdio.h>
#include <winsock2.h>
#include <string.h>
void error(const char *);
int main()
{
WSAData data;
WSAStartup( MAKEWORD( 2, 2 ), &data );
int sock, n;
int length;
struct sockaddr_in server, from;
struct hostent *hp;
char buffer[256];
unsigned short serverPort = 27072;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("socket");
server.sin_family = AF_INET;
hp = gethostbyname("localhost");//have also tried my url
if (hp==0) error("Unknown host");
memmove((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length);
server.sin_port = htons(serverPort);
length = sizeof(struct sockaddr_in);
printf("Please enter the message: ");
memset(buffer, 0, 256);
fgets(buffer, 255, stdin);
n = sendto (sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&server, length);
if (n < 0) error("Sendto");
printf("sent %i bytes\n", n);
n = recvfrom(sock, buffer, 256, 0, (struct sockaddr *)&server, &length);
if (n < 0) error("recvfrom");
//write(1,"Got an ack: ", 12);
//write(1, buffer, n);
printf("Got msg: %s\n",buffer);
closesocket(sock);
WSACleanup();
return(0);
}
void error(const char *msg)
{
perror(msg);
exit(0);
}
服务器代码:
#include <stdio.h>
#include <winsock2.h>
#include <string.h>
void error(const char *);
int main()
{
WSAData data;
WSAStartup( MAKEWORD( 2, 2 ), &data );
int sock, length, n;
int fromlen;
struct sockaddr_in server;
struct sockaddr_in from;
char buf[1024];
unsigned short serverPort = 27072;
sock=socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("Opening socket");
length = sizeof(server);
memset(&server, 0, length);
server.sin_family = AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(serverPort);
if (bind(sock,(struct sockaddr *)&server, length)<0) error ("binding");
fromlen = sizeof(struct sockaddr_in);
while(1)
{
n = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen);
if (n<0) error("recvfrom");
//write(1,"Received a datagram: ", 21);
//write(1,buf,n);
printf("Received a datagram: %s", buf);
n = sendto(sock, "Got your message\n",17,0,(struct sockaddr *)&from,fromlen);
if (n<0)error("sendto");
}
closesocket(sock);
WSACleanup();
return 0;
}
void error (const char *msg)
{
perror(msg);
exit(0);
}