Created
February 17, 2021 07:38
-
-
Save R3D9477/278b6e40b29fd6cca6ef2b5a90832652 to your computer and use it in GitHub Desktop.
C++ UDP Sender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
#include <errno.h> | |
#include <string.h> | |
#define SENDER_PORT 55555 | |
#define RECEIVER_PORT 55554 | |
#define RECEIVER_ADDR "0.0.0.0" | |
#define MESSAGE "Hello from UDP!\n" | |
int main() | |
{ | |
int sock; | |
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0) { | |
sockaddr_in sender_addr; | |
sender_addr.sin_family = AF_INET; | |
sender_addr.sin_port = htons(SENDER_PORT); | |
if (bind(sock, (sockaddr*)(&sender_addr), sizeof(sender_addr)) >= 0) { | |
sockaddr_in receiver_addr; | |
receiver_addr.sin_family = AF_INET; | |
receiver_addr.sin_port = htons(RECEIVER_PORT); | |
if (inet_pton(AF_INET, "0.0.0.0", &receiver_addr.sin_addr) > 0) { | |
if (sendto(sock, MESSAGE, strlen(MESSAGE), 0, (sockaddr*)(&receiver_addr), sizeof(receiver_addr)) > 0) | |
std::cout << "Message sent" << std::endl; | |
else | |
std::cout << "Unable To Send Data..." << std::endl; | |
} | |
close(sock); | |
return 0; | |
} | |
} | |
std::cout << errno << " - " << strerror(errno) << std::endl; | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment