我写了一个简单的程序,它应该发送长度不断变化的UDP包。 UDP数据包的大小可以随时更改。 用户可以通过命令行输入端口号以及消息的最小和最大长度。在有效载荷的前32位是UDP包号。 我使用sendto()函数,我收到一个有效的返回号码但是当我尝试使用UDP服务器程序(例如SocketTest)验证它时,我无法在另一端看到任何数据。 以下是我的代码:
#define DEFAULT_PORT 355
int Port = DEFAULT_PORT; // Port to send data to
int Max_Length = 100, Min_Length = 8; //default values
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum);
char genRandom()
{
return alphanum[rand() % stringLength];
}
void usage()
{
cout << "-m:int Define minimum UDP packet size" << endl;
cout << " -M:int Define maximum UDP packet size" << endl;
cout << " -p:int Define remote port" << endl;
}
void ValidateArgs(int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++)
{
if ((argv[i][0] == '-'))
{
switch (argv[i][1])
{
case 'm':
if (strlen(argv[i]) > 3) {
Min_Length = (double)atoi(&argv[i][3]);
}
break;
case 'M':
if (strlen(argv[i]) > 3) {
Max_Length = (double)atoi(&argv[i][3]);
}
break;
case 'p':
if (strlen(argv[i]) > 3) {
Port = atoi(&argv[i][3]);
}
break;
default:
usage();
break;
}
}
}
}
int main(int argc, char **argv)
{
sockaddr_in my_addr;
ValidateArgs(argc, argv);
WSADATA wsd;
int Result = WSAStartup(MAKEWORD(2, 2), &wsd);
if (Result != NOERROR) {
cout << "WSAStartup Failed!" << endl;
exit(0);
}
SOCKET sock;
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
cout << "Socket Failer with error: " << WSAGetLastError() << endl;
WSACleanup();
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr("192.68.0.31");
my_addr.sin_port = htons((short)Port);
string data = "";
/*Get a Random String Length*/
random_device seeder;
int UDP_Packet_number = 1;
string buffer_data;
mt19937 engine(seeder());
uniform_int_distribution<int> dist(Min_Length, Max_Length);// user input from command line
int StrLen = dist(engine);
while (true) {
/*Get aRandom String*/
for (int i = 0; i < StrLen; ++i)
{
data += genRandom();
}
srand(time(0));
StrLen = dist(engine);
char numbr_pkg[4];
numbr_pkg[0] = (UDP_Packet_number >> 24) & 0xff;
numbr_pkg[1] = (UDP_Packet_number >> 16) & 0xff;
numbr_pkg[2] = (UDP_Packet_number >> 8) & 0xff;
numbr_pkg[3] = UDP_Packet_number & 0xff;
/*First 32 Bits is the packet Number*/
for (int i = 0; i < 4; i++) {
buffer_data += numbr_pkg[i];
}
buffer_data += data;
data = "";
int result = sendto(sock, buffer_data.c_str(), buffer_data.length(), 0, (SOCKADDR *)&my_addr, sizeof(my_addr));
//cout << result << " " << buffer_data.length() << endl;
buffer_data = "";
UDP_Packet_number++;
}
return 0;
}
你能告诉我我做错了什么吗?我想找很长时间的解决方案。