Skip to content

Instantly share code, notes, and snippets.

@jimfinnis
Created October 4, 2013 10:13
Show Gist options
  • Select an option

  • Save jimfinnis/6823802 to your computer and use it in GitHub Desktop.

Select an option

Save jimfinnis/6823802 to your computer and use it in GitHub Desktop.

Revisions

  1. jimfinnis created this gist Oct 4, 2013.
    33 changes: 33 additions & 0 deletions gistfile1.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@

    #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;
    }