Lab 2: Useful Code Snippets

Manipulating memory

     void *memmove(void *dst, const void *src, size_t len);

     void *memcpy(void *dst, const void *src, size_t len);

     void *memset(void *b, int c, size_t len);

Memmove deals with the case where the destination and source buffers overlap. Memcpy does not.

UDP Socket tricks

How to create a UDP socket:

if ((s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
	perror ("socket");
	exit (1);

How to set the port on which you'll be listening (a.k.a binding the socket)

struct sockaddr_in   addr;

 *  Bind a port to receive data on
memset (&addr, 0, sizeof(addr));
addr.sin_family      = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port        = htons(0);   /* 0 means we don't care */
/* for server: addr.sin_port = htons (svc_port); where svc_port is the
   well-known port for that RPC service.

if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
	perror ("bind");
	exit (-1);

How to read/write packets from a UDP socket:

ssize_t recvfrom(int s, void *buf, size_t len, int flags, 
		 struct sockaddr *from, int *fromlen);

ssize_t sendto(int s, const void *msg, size_t len, int flags,
             const struct sockaddr *to, int tolen);

Clock Information

How to get the number of clock ticks since boot time:

clock_t  ticks;
ticks = times(NULL);   

How to convert those clock ticks into seconds:

int ticks_per_second = sysconf (_SC_CLK_TCK);


Read with timeout stuff:

/* Note: s is the UDP socket */
	struct timeval timeout;
	fd_set  readfs;
	ssize_t  bytes_read;

	timeout.tv_sec = 0;
	timeout.tv_usec = 100;

	FD_ZERO( &readfds );
	FD_SET ( s, &readfds );

	res = select(s+1, &readfds, NULL, NULL, &timeout);
	if (res == -1) {
		perror ("select");
	if (res > 0) {
		bytes_read = recvfrom(s, buf, len, flags, from fromlen);

        /* See if anything's expired */

Defining new types

Lab 2 requires you to define three new types. In C, new types are declared using the typedef keyword.

typedef int color; 
color tas_favorite_color;

struct _SVCDAT {
     int  socket;
typedef struct _SVCDAT SVCDAT;

typedef struct _CLIREQ {
      int  client_id;

Constantine Sapuntzakis
February 28, 1997