Created
October 4, 2013 10:13
-
-
Save jimfinnis/6823802 to your computer and use it in GitHub Desktop.
C++/C code to send UDP packets.
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 <stdio.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
#include <strings.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include "udpclient.h" | |
bool udpSend(const char *msg){ | |
sockaddr_in servaddr; | |
int fd = socket(AF_INET,SOCK_DGRAM,0); | |
if(fd<0){ | |
perror("cannot open socket"); | |
return false; | |
} | |
bzero(&servaddr,sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = inet_addr(HOSTNAME); | |
servaddr.sin_port = htons(PORT); | |
if (sendto(fd, msg, strlen(msg)+1, 0, // +1 to include terminator | |
(sockaddr*)&servaddr, sizeof(servaddr)) < 0){ | |
perror("cannot send message"); | |
close(fd); | |
return false; | |
} | |
close(fd); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!