Created
July 18, 2011 04:36
-
-
Save jedisct1/1088555 to your computer and use it in GitHub Desktop.
Stupid UDP sender
This file contains hidden or 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 <stdlib.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#define MAX_PACKET 20000U | |
void usage(void) { | |
puts("\nUsage: udpsend <host> <port>\n"); | |
exit(EXIT_SUCCESS); | |
} | |
struct addrinfo *resolve(const char * const host, const char * const port) | |
{ | |
struct addrinfo *ai, hints; | |
memset(&hints, 0, sizeof hints); | |
hints.ai_family = AF_UNSPEC; | |
hints.ai_flags = 0; | |
hints.ai_socktype = SOCK_DGRAM; | |
hints.ai_protocol = IPPROTO_UDP; | |
const int gai_err = getaddrinfo(host, port, &hints, &ai); | |
assert(gai_err == 0); | |
return ai; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 3) { | |
usage(); | |
} | |
const char * const host = argv[1]; | |
const char * const port = argv[2]; | |
struct addrinfo *ai = resolve(host, port); | |
int kindy = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); | |
char buf[MAX_PACKET]; | |
const ssize_t nbread = read(0, buf, sizeof buf); | |
assert(nbread > (ssize_t) 0); | |
assert(sendto(kindy, buf, nbread, 0, ai->ai_addr, ai->ai_addrlen) | |
== nbread); | |
assert(kindy != -1); | |
freeaddrinfo(ai); | |
close(kindy); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment