9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

udp.c (1094B)


      1 #include <u.h>
      2 #define NOPLAN9DEFINES
      3 #include <libc.h>
      4 #include <ip.h>
      5 
      6 #include <sys/socket.h>
      7 #include <netinet/in.h>
      8 
      9 /*
     10  *  prefix of all v4 addresses
     11  *  copied from libip because libc cannot depend on libip
     12  */
     13 static uchar v4prefix[IPaddrlen] = {
     14 	0, 0, 0, 0,
     15 	0, 0, 0, 0,
     16 	0, 0, 0xff, 0xff,
     17 	0, 0, 0, 0
     18 };
     19 
     20 long
     21 udpread(int fd, Udphdr *hdr, void *buf, long n)
     22 {
     23 	struct sockaddr_in sin;
     24 	socklen_t len;
     25 
     26 	len = sizeof sin;
     27 	n = recvfrom(fd, buf, n, 0, (struct sockaddr*)&sin, &len);
     28 	if(len != sizeof sin){
     29 		werrstr("recvfrom acting weird");
     30 		return -1;
     31 	}
     32 	if(n < 0)
     33 		return -1;
     34 	memset(hdr, 0, sizeof *hdr);
     35 	memmove(hdr->raddr, v4prefix, IPaddrlen);
     36 	*(u32int*)(hdr->raddr+12) = *(u32int*)&sin.sin_addr;
     37 	*(u16int*)hdr->rport = *(u16int*)&sin.sin_port;
     38 	return n;
     39 }
     40 
     41 long
     42 udpwrite(int fd, Udphdr *hdr, void *buf, long n)
     43 {
     44 	struct sockaddr_in sin;
     45 
     46 	memset(&sin, 0, sizeof sin);
     47 	sin.sin_family = AF_INET;
     48 	*(u32int*)&sin.sin_addr = *(u32int*)(hdr->raddr+12);
     49 	*(u16int*)&sin.sin_port = *(u16int*)hdr->rport;
     50 	return sendto(fd, buf, n, 0, (struct sockaddr*)&sin, sizeof sin);
     51 }
     52