GPSBots.com
Home :: [Photos] : [Tutorials] : [Projects] : [Resources] : [About Us]

Linux Tutorial: Transmit UDP Packet

transmit_udp.c - Download Source Code
UDP packets are easily sent with linux. A UDP packet is simply broadcasted out, they don't get any responses and aren't guaranteed to arrive in order or at all. If your data must arrive, you should use TCP. The following code was compiled successfully under Slackware 10 on a Mini-ITX board.
To Compile: g++ transmit_udp.c -g -o transmit_udp -O3
-g to allow gdb to work
-o transmit_udp is the output name
-O3 is the optimization level

#include <arpa/inet.h>      // network
#include <stdio.h>      // perror
#include <sys/socket.h>      // network
#include <unistd.h>      // exit
#include <string.h>      // memset

#define TARGET_IP "192.168.1.50"
#define TARGET_PORT 3000

int main(void) {
     struct sockaddr_in si_output;      // my socket
     int s;      // socket

     if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { perror("socket"); _exit(1);}
     memset((char*)&si_output, sizeof(si_output), 0);
     si_output.sin_family = AF_INET;
     si_output.sin_port = htons(TARGET_PORT);
     if (inet_aton(TARGET_IP, &si_output.sin_addr) == 0) { perror("inet_aton() failed"); _exit(1); }

     char buf[50] = "Test UDP Packet";
int len=strlen(buf);
     if (sendto(s, buf, len, 0, (struct sockaddr *)&si_output, sizeof(si_output)) != len) {
          perror("Error: sendto()");
          _exit(1);
     }
     
     close(s);
     return 0;
}

Sample Output:

Use sniff_packets to catch the data, or install a sniffer such as Ethereal.