development:cpp:upd

C++ send UDP packet

#include <arpa/inet.h>
#include <string>
#include <cstring>
 
void udpentry(std::string message) {
	struct sockaddr_in myaddr;
	int sock;
	memset(&myaddr, 0, sizeof(myaddr));
	myaddr.sin_family=AF_INET;
	myaddr.sin_port=htons(10001);
 
	if((sock=socket(AF_INET, SOCK_DGRAM, 0))<0) {
		perror("Failed to create socket");
		exit(EXIT_FAILURE);
	}
 
	if(bind(sock,( struct sockaddr *) &myaddr, sizeof(myaddr))<0) {
		perror("bind failed");
		exit(EXIT_FAILURE);
	}
	inet_pton(AF_INET,"192.168.180.54",&myaddr.sin_addr.s_addr);
	myaddr.sin_port=htons(514);
 
	if(sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&myaddr, sizeof(myaddr))!=message.size()) {
		perror("Mismatch in number of bytes sent");
		exit(EXIT_FAILURE);
	}
	close(sock);
}
 
int  main()
{
	udpentry("%TST-1-000001 TEST SYSLOG C++");
 
	return 0;
}
  • development/cpp/upd.txt
  • Last modified: 2019/10/31 09:04
  • by 127.0.0.1