[英]recvfrom() is stuck and I don't know why
我有一个项目要为我的学校做。 目的是创建一个使用回显服务(C编程)的类似ping的程序。 回显服务通常在UDP端口7上运行,并且必须使用简单TCP / IP进行激活。 如果收到一条消息,Echo应该回复一条消息。 这是我编写的代码:
// ping.cpp : entry point
#include "ping.h"
#pragma comment(lib,"WS2_32") //Library
int main(int argc, char *argv[]) {
//Variable
char IPAdress[] = "127.0.0.1";
WORD versionProtocoleSocket;
SOCKET pingSocket;
struct sockaddr_in destination;
char packet[MAX_PACKET_SIZE], reply[MAX_PACKET_SIZE];
int err, msgLength;
//Initialisation of Windows Socket
printf("Initialising WSA 2.2...\n");
versionProtocoleSocket = MAKEWORD(2, 2);
err = initialiseSocket(versionProtocoleSocket);
if (err != 0) {
errSocket(err);
printf("The program will stop\n");
_getch();
return EXIT_FAILURE;
}
else
printf("Initialisation success\n\n");
//Socket creation
printf("Socket creation...\n");
if ((pingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) {
printf("Can't create socket\nThe program is going to stop\n");
_getch();
return EXIT_FAILURE;
}
else
printf("Creation sucess\n\n");
//Préparation des variables pour l'utilisation de la fonction sendto()
destination.sin_family = AF_INET;
destination.sin_port = htons(7);
destination.sin_addr.s_addr = inet_addr(adresseIP);
msgLength = sizeof(message);
int addrSize = sizeof(destination);
//Beginning of ping
for (int i = 0; i < 5; i++)
{
//Sending
if (sendto(pingSocket, message, messageLength, 0, (struct sockaddr *)&destination, addrSize) == SOCKET_ERROR)
printf("Can't send message : %d\n", WSAGetLastError());
else
printf("Message %d sent\n", i);
//Reception
if (recvfrom(pingSocket, reply, MAX_PACKET_SIZE, 0, NULL, NULL) == SOCKET_ERROR)
printf("Error : %d\n", WSAGetLastError());
else
printf("Message %d received\n", i);
}
_getch();
return EXIT_SUCCESS;
}
int initialiserSocket(WORD version) {
WSADATA wsaData;
int err = WSAStartup(version, &wsaData);
return err;
}
void errSocket(int err) {
switch (err) {
case WSASYSNOTREADY:
printf("System is not ready\n");
break;
case WSAVERNOTSUPPORTED:
printf("Unsuported protocol version\n");
break;
case WSAEINPROGRESS:
printf("A version is already running\n");
break;
case WSAEPROCLIM:
printf("Max task reached\n");
break;
case WSAEFAULT:
printf("pointer lpWSAData is not valid\n");
break;
default:
printf("Unknown error\n");
break;
}
}
现在ping.h代码:
#pragma once
#include "stdio.h"
#include "winsock2.h"
#include "conio.h"
#include "stdint.h"
int initialiseSocket(WORD version);
void errSocket(int err);
#define MAX_PACKET_SIZE 10*1024
问题是我的程序卡在recvfrom函数上,我不知道为什么。 你可以解释吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.