* UdpTest.cpp
cpp
/*
* On client:
* gcc udp_test_windows.c -o udp_test_windows -lws2_32
* ./udp_tset_windows x.x.x.x 4665 # Replace x.x.x.x with your server IP address
* On server:
* sudo tcpdump -i any udp port 4665 -nn -XX
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
int sendUdp(const char *ip, unsigned short port, const char *message) {
WSADATA wsaData;
SOCKET sockfd;
struct sockaddr_in servaddr;
int ret_code;
/* Initialize Winsock */
if ((ret_code = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) {
fprintf(stderr, "WSAStartup failed with error: %d\n", WSAGetLastError());
return ret_code;
}
/* Create socket */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
ret_code = WSAGetLastError();
fprintf(stderr, "Socket creation failed with error: %d\n", ret_code);
WSACleanup();
return ret_code;
}
memset(&servaddr, 0, sizeof(servaddr));
/* Set server address and port */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &servaddr.sin_addr) <= 0) {
fprintf(stderr, "Invalid address/ Address not supported\n");
closesocket(sockfd);
WSACleanup();
return 2; /* Custom error code for invalid address */
}
/* Send message to server */
int n = sendto(sockfd, message, strlen(message), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
if (n == SOCKET_ERROR) {
ret_code = WSAGetLastError();
fprintf(stderr, "Send failed with error: %d\n", ret_code);
closesocket(sockfd);
WSACleanup();
return ret_code;
}
closesocket(sockfd);
WSACleanup();
return 0;
}
int main(int argc, char* argv[])
{
/* E:\Projects\VS_Projects\UdpTest\Debug\UdpTest.exe x.x.x.x 4665 */
if (argc != 3) {
fprintf(stderr, "Usage: %s <IP> <port>\n", argv[0]);
return 1;
}
const char* ip = argv[1];
unsigned short port = atoi(argv[2]);
const char* message = "Hello, aMule!";
sendUdp(ip, port, message);
printf("Message sent to %s:%d\n", ip, port);
return 0;
}
Add port 4665/udp to the firewall configuration:
bash
default_zone=$(firewall-cmd --get-default-zone)
firewall-cmd --permanent --zone=${default_zone} --add-port=4665/udp
firewall-cmd --reload
firewall-cmd --state
firewall-cmd --list-all --zone=${default_zone}
Test output: